In this article we will learn how to loop through array backwards in JavaScript.
It is very common to loop through array backwards in JavaScript in JavaScript.
Problem
Now we have a problem, which is that we want to iterate over the array, but from the last to the first.
Imagine we have an array like this:
const array = [1, 2, 3, 4, 5, 6];
And we want to iterate from the last to the first so that the result becomes like this:
6 5 4 3 2 1
How to solve this problem?
The solution to this problem is easy, and there are more than one solution to this problem:
- Using reverse
for-loop
- Using Using
Array.reverse()
method - Using
Array.reduceRight()
method
Loop through array backwards using reveres for loop
We can iterate over array starting from the end of the array towards the beginning of the array using for
.
Let's see an example:
// Array
const array = [1, 2, 3, 4, 5, 6];
// Iterate from the end
for (let i = array.length - 1; i >= 0; i--) {
console.log(array[i]);
}
Output
6
5
4
3
2
1
Loop through array backwards using Array.reverse()
We can use Array.reverse()
to reverse elements and make our iterate.
Example
// Array
const array = [1, 2, 3, 4, 5, 6];
// Reversed array
const reverse = array.reverse();
// Iterate over elements
for (let i = 0; i < reverse.length; i++) {
console.log(reverse[i]);
}
Output
6
5
4
3
2
1
We can use forEach
as well.
// Array
const array = [1, 2, 3, 4, 5, 6];
// Reverse
const reverse = array.reverse();
// Iterate using `forEach`
reverse.forEach(ele => {
console.log(ele);
})
Loop through array backwards using Array.reduceRight()
We can use reduceRight
to solve this problem as well.
// Array
const array = [1, 2, 3, 4, 5, 6];
// Iterate
array.reduceRight((_, item) => console.log(item), null);
Output
6
5
4
3
2
1
Thank you for reading
Thank you for reading my blog. 🚀