Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate over a list of elements from last element to first using underscore?

how do i iterate over a list from end to beginning using _.each in underscore?

lister = ['a', 'c', 'd', 'w', 'e'];
_.each(_.range(lister.length, 0 ,-1), function (val,i) {
   console.log(val);
}, lister);

this prints number 5 to 1 in console. Is it a good idea to use underscore's _.each in place of tradition "for" loop?

like image 972
scottydelta Avatar asked May 27 '13 05:05

scottydelta


3 Answers

All of these answers will mutate the array which is not what he wants to do, unless you want to add another .reverse() after each time you run it.

But since oyu are using loDash you can easily avoid this by wrapping the array inside of a clone or cloneDeep within the each() call

var letterArray = [ 'a', 'b', 'c', 'd', 'e' ];
_.each( _.clone(letterArray).reverse(), function(v, i) {
   console.log( i+1 );
});

this will log 5, 4, 3, 2, 1 without affecting the original array.

like image 58
sean6bucks Avatar answered Nov 09 '22 20:11

sean6bucks


Just reverse the array before you iterate over it?

lister.reverse();

To answer your _.each() vs for loop question, have a look here.

like image 10
tom-19 Avatar answered Nov 09 '22 21:11

tom-19


Underscore does not give you a way to iterate in reverse a collection, just forward. Reversing the array solves the problem as much as reversing the way the elements are put in the array does.

One possible solution for traversing in reverse is falling back to plain Javascript:

for (var i = arr.length; i-- > 0; )
like image 8
Alejandro Pablo Tkachuk Avatar answered Nov 09 '22 20:11

Alejandro Pablo Tkachuk