Leon Gaban
Leon Gaban

Reputation: 39028

What is the lodash equivalent for a reverse for loop?

I'm trying to figure out how to recreate this type of reverse for loop in lodash:

Here the last item of the Array will be iterated on first:

for (var j=quotes.data[data_location].length-1; j>=0; j--)

For the regular for loop:

for (var j=0; j < quotes.data[data_location].length; j++)

I can accomplish this with lodash's _.each:

_.each(quotes.data[data_location], function(quote) {

Upvotes: 7

Views: 7942

Answers (1)

alex
alex

Reputation: 490283

Lodash has forEachRight().


Without lodash, you could call reverse() on the loop first, which will mutate the original array. If you don't want to do this, you can create a shallow copy of the array with slice().

Keep in mind that this will essentially add another iteration in your code. If this is performance critical, a backwards counting for loop is a good idea.

Upvotes: 16

Related Questions