Javascript - Loop through array backwards with forEach
Solution 1:
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.
Solution 2:
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
.