Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Loop through array backwards with forEach

Is there a way to loop backwards through an array using forEach (not any other kind of loop, I know how to do with with a for / standard ways) and without actually reversing the array itself?

like image 652
Mankind1023 Avatar asked Oct 16 '22 19:10

Mankind1023


People also ask

How do we traverse an array starting from the end to the beginning of the array?

You can traverse through an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

Can FOR loops go backwards C#?

In C#, using Visual Studio 2005 or later, type 'forr' and hit [TAB] [TAB]. This will expand to a for loop that goes backwards through a collection.


2 Answers

let arr = [1, 2, 3];

arr.slice().reverse().forEach(x => console.log(x))

will print:

3
2
1

arr will still be [1, 2, 3], the .slice() creates a shallow copy.

like image 96
naartjie Avatar answered Oct 19 '22 07:10

naartjie


There is a similar array method that has a reverse counter part, reduce comes together with reduceRight:

const array = ['alpha', 'beta', 'gamma'];

array.reduceRight((_, elem) => console.log(elem), null);

When using it for the requested purpose, make sure to provide a second argument. It can be null or anything else. Also note that the callback function has as first argument the accumulator, which you don't need for this purpose.

If including a library is an option:

Lodash: forEachRight.

like image 33
trincot Avatar answered Oct 19 '22 07:10

trincot