Loop through an array backward in JavaScript
This post will discuss how to loop through an array backward in JavaScript.
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.
|
1 2 3 4 5 |
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.
|
1 2 3 4 5 6 |
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:
|
1 2 3 4 5 6 |
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.
|
1 2 3 |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)