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?
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.
Just reverse the array before you iterate over it?
lister.reverse();
To answer your _.each()
vs for loop
question, have a look here.
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; )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With