Reverse an array java script
Reverse an Array in JavaScript
The Problem
You have an array in JavaScript and you need to reverse the order of its elements.
The Solution
The easiest way to reverse an array in JavaScript is to use the built-in reverse()
method. This method reverses the order of the elements in place and returns the reversed array.
let arr = [1, 2, 3, 4, 5];
arr.reverse(); // [5, 4, 3, 2, 1]
If you don't want to modify the original array, you can create a copy of it and reverse the copy using slice()
and reverse()
:
let arr = [1, 2, 3, 4, 5];
let reversedArr = arr.slice().reverse(); // [5, 4, 3, 2, 1]
You can also reverse an array using a loop:
let arr = [1, 2, 3, 4, 5];
let reversedArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
reversedArr.push(arr[i]);
}
// [5, 4, 3, 2, 1]
Explanation
JavaScript's reverse()
method reverses the order of the elements in an array in place. This means that it modifies the original array and returns a reference to the same array.
The slice()
method creates a shallow copy of an array. This means that it creates a new array with the same elements as the original array. If you pass no arguments to slice()
, it will copy the entire array. If you pass arguments, it will copy the elements between the specified indexes.
The loop solution works by iterating over the original array in reverse order and pushing each element onto a new array.
Conclusion
Reversing an array in JavaScript is easy using the reverse()
method or a loop. If you need to reverse an array without modifying the original, you can create a copy of it using slice()
.