How to iterate over a list of elements from the last element to the first using an underscore?

how to iterate over a list from end to top using _.each in underscore?

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

this displays a number from 5 to 1 in the console. Is it a good idea to use the underscore _. is this instead of the traditional pro loop?

+8
source share
3 answers

Just cancel the array before iterating over it?

 lister.reverse(); 

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

+8
source share

Underscore does not give you the ability to iterate over the collection, just ahead. Reversing an array solves the problem in the same way as reversing the way elements are entered into the array.

One possible solution for moving in the opposite direction is to return to plain Javascript:

 for (var i = arr.length; i-- > 0; ) 
+7
source share

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

But since oyu uses loDash, you can easily avoid this by wrapping the array inside a clone or cloneDeep in each () call

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

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

0
source share

All Articles