To loop through an array in reverse order:
- Use the
slice()
method to create a copy of the array. - Use the
reverse()
method to reverse the copied array. - Call the
forEach()
method on the reversed array.
index.js
const arr = ['a', 'b', 'c'];
arr
.slice()
.reverse()
.forEach(element => {
console.log(element); // π️ c, b, a
});
The first step is to use the Array.slice() method to create a shallow copy of the array.
This is necessary because the Array.reverse() method changes the contents of the original array in place.
Calling the slice()
method with no parameters returns a shallow copy of original array, which we can reverse.
index.js
const arr = ['a', 'b', 'c']; const copy = arr.slice(); console.log(copy); // π️ ['a', 'b', 'c']
The reverse()
method reverses an array in place and returns the result.
index.js
const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // π️ ['c', 'b', 'a'] console.log(arr); // π️ ['c', 'b', 'a']
Notice that the original array stored in the arr
variable was also reversed.
This is the reason we created a shallow copy in advance - to avoid changing the original array.
The last step is to use the Array.forEach method on the reversed array.
index.js
const arr = ['a', 'b', 'c']; arr .slice() .reverse() .forEach(element => { console.log(element); // π️ c, b, a });
The function we passed to the Array.forEach()
method gets called with each element in the array.
The forEach()
method returns undefined
, so we have to perform some kind of mutation to persist the state.
An alternative approach is to use the spread syntax (...) to create a shallow copy of the array.
Use forEach() on an Array in Reverse Order using spread syntax (...)
To use the forEach()
method on an array in reverse order:
- Use the spread syntax (...) to create a copy of the array.
- Use the
reverse()
method to reverse the copied array. - Call the
forEach()
method on the reversed array.
index.js
const arr = ['a', 'b', 'c']; [...arr].reverse().forEach(element => { console.log(element); // π️ c, b, a });
The spread syntax (...) unpacks the values of the original array into a new array, creating a shallow copy.
We then reverse the copy to avoid mutating the original array and call the forEach()
method on the reversed array.
Use forEach() on an Array in Reverse Order by using the index
You can also use the forEach()
method in reverse order by using the current index.
index.js
const arr = ['a', 'b', 'c']; arr.forEach((_element, index) => { const last = arr[arr.length - 1 - index]; console.log(last); // π️ c, b, a });
The second argument the callback function gets called with is the index of the current iteration.
We subtract 1
and the current index from the array's length to iterate over the array in reverse order.
For example, on the first iteration, we get an index of arr.length - 1 - 0
.
For an array that has 3
, elements this evaluates to 2
, which is the last index in the array.
JavaScript indexes are zero-based, so the first element in an array has an index of 0
and the last element has an index of array.length - 1
.
On each iteration, we subtract 1
and the current index from the array's length to map over the array in reverse order.
Iterate over an array in reverse using a basic for
loop
Alternatively, you can iterate over the array in reverse order by using a basic for
loop.
index.js
const arr = ['a', 'b', 'c']; for (let index = arr.length - 1; index >= 0; index--) { console.log(arr[index]); // π️ c, b, a }
We initialized the index to arr.length - 1
(the last index in the array).
On each iteration, we decrement the index for as long as the current index is greater than or equal to 0
.
Use forEach() on an Array in Reverse Order by using reduceRight
You can also use the Array.reduceRight method to iterate over an array in reverse order.
index.js
const arr = ['a', 'b', 'c'];
const result = arr.reduceRight((accumulator, last) => {
console.log(last);
return accumulator.concat(last);
}, []);
console.log(result); // π️ [ 'c', 'b', 'a' ]
The reduceRight function is employed to iteratively apply a specified function to the elements of an array, starting from the rightmost element and moving towards the left, ultimately condensing the array into a single value.
In this context, the accumulator variable is set initially as an empty array, as indicated by the second argument provided to the Array.reduceRight() method.
No comments:
Post a Comment