I'd like to return every second item from a list, using Underscore.
I guess I could do something like this:
var i = 0;
_.filter([1,2,3,4...], function(item) {
i++;
return (i%2 == 0);
});
but is there a more elegant way, native to Underscore?
I'd like to return every second item from a list, using Underscore.
I guess I could do something like this:
var i = 0;
_.filter([1,2,3,4...], function(item) {
i++;
return (i%2 == 0);
});
but is there a more elegant way, native to Underscore?
Share Improve this question asked Apr 8, 2014 at 16:28 RichardRichard 65.7k135 gold badges356 silver badges571 bronze badges 4-
No need for underscore here... you can simply do
[1,2,3,4...].filter(function(_,i){ return i%2;})
it's fully supported inall non-really-ancient browsers (yes, even IE9). – Benjamin Gruenbaum Commented Apr 8, 2014 at 16:33 - i would suggest using function takeEveryN(item, index) {return index % this == 0;}; and calling it like _.filter([1,2,3,4], takeEveryN, 2); so you can hop over different numbers of items later... – dandavis Commented Apr 8, 2014 at 16:36
-
@dandavis that's confusing since there already is an
Array.prototype.every
that does something else. – Benjamin Gruenbaum Commented Apr 8, 2014 at 16:37 - 1 mine's not an [] prop, but i'll concede the point and edit my ment to remove ambiguity. good input. my main point was to use a named function because it encourages reuse and defining functions closer to global makes the code faster to run in V8 if not elsewhere since it doesn't re-parse the function as much... – dandavis Commented Apr 8, 2014 at 16:38
3 Answers
Reset to default 5The function which is getting called by _.filter
will get the current index as well, as the second parameter and you can make use of that like this
console.log(_.filter([1, 2, 3, 4], function(item, index) {
return index % 2 == 0;
}));
# [ 1, 3 ]
Since you want to start from the second element, you just have to change the condition a little, like this
console.log(_.filter([1, 2, 3, 4], function(item, index) {
return index % 2 == 1;
}));
# [ 2, 4 ]
Alternatively, you can use the native Array.prototype.filter
in the same way, like this
console.log([1, 2, 3, 4].filter(function(item, index) {
return index % 2 == 1;
}));
_.filter([1,2,3,4...], function(item, index) {
return (index % 2 == 0);
});
filter
predicate accepts two parameters - item value and index value.
var test = [1,2,3,4];
var tt = _.first(_.rest([5, 4, 3, 2, 1]));
console.log(tt);
Fiddle
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745361575a4624384.html
评论列表(0条)