admin管理员组

文章数量:1426086

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
Add a ment  | 

3 Answers 3

Reset to default 5

The 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

本文标签: javascriptReturn every second item from a list with UnderscorejsStack Overflow