There are several methods to loop through the array in JavaScript in the reverse direction:
1. Using reverse for-loop
The standard approach is to loop backward using a for-loop starting from the end of the array towards the beginning of the array.
var arr = [1, 2, 3, 4, 5];
for (var i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
2. Using Array.prototype.reverse()
function
We know that forEach
goes through the array in the forward direction. To loop through an array backward using the forEach
method, we have to reverse the array. To avoid modifying the original array, first create a copy of the array, reverse the copy, and then use forEach
on it. The array copy can be done using slicing or ES6 Spread operator.
var arr = [1, 2, 3, 4, 5];
arr.slice().reverse()
.forEach(function(item) {
console.log(item);
});
Alternatively, you can use the Object.keys() method to get keys:
var arr = [1, 2, 3, 4, 5];
Object.keys(arr).reverse()
.forEach(function(index) {
console.log(arr[index]);
});
3. Using Array.prototype.reduceRight() function
The reduceRight()
method executes the callback function once for each element present in the array, from right-to-left. The following code example shows how to implement this.
var arr = [1, 2, 3, 4, 5];
arr.reduceRight((_, item) => console.log(item), null);
That’s all about looping through an array backward in JavaScript.
Source :- https://www.techiedelight.com/loop-through-array-backwards-javascript/