An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
For Loop through an array in backward direction 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.
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);
Thats all about looping through an array backward in JavaScript.
Source :- https://www.techiedelight.com/loop-through-array-backwards-javascript/
Original Link: https://dev.to/sh20raj/for-loop-through-an-array-in-backward-direction-in-javascript-421i
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To