Array reversal methods in JavaScript
#JavaScript
Table of Contents
In JavaScript there are various methods to reverse arrays. Here we will explore some of them.
Custom functions
Previously, to reverse an array, a common approach was to create a custom function. This function would iterate through the array in reverse and build a new array, which was then returned by the function.
Here is an example:
function reverseArray<T>(arr: T[]) {
const result = [];
let i = arr.length - 1;
while (i >= 0) {
result.push(arr[i]);
i--;
}
return result;
}
Alternatively using optimized methods where elements were swapped between the start and end of the array in pairs, resulting in the modification of the original array.
Here's an example:
function reverseArray<T>(arr: T[]) {
let start = 0;
let end = arr.length - 1;
while (start < end) {
const element = arr[start];
arr[start] = arr[end];
arr[end] = element;
start++;
end--;
}
return arr;
}
ES6 .reverse()
method
In ES6, the .reverse()
method was introduced which mutates the original array and returns a reference to the modified array. To preserve the original array, it is necessary to clone it before applying .reverse()
.
const originalArray = [1, 2, 3];
const reversedArray = originalArray.reverse();
console.log(originalArray); // [3, 2, 1]
console.log(reversedArray); // [3, 2, 1]
console.log(originalArray === reversedArray); // true
const originalArray2 = [1, 2, 3];
const reversedArray2 = [...originalArray2].reverse();
// const reversedArray2 = Array.from(secondArr).reverse();
// const reversedArray2 = secondArr.slice().reverse();
// const reversedArray2 = [].concat(secondArr).reverse();
console.log(originalArray2); // [1, 2, 3]
console.log(reversedArray2); // [3, 2, 1]
console.log(originalArray2 === reversedArray2); // false
ES2023 .toReversed()
method
In ES2023, a new method .toReversed()
was introduced. Unlike .reverse()
this method doesn't mutate the original array. Instead it creates a new array with elements in reverse order
const originalArray = [1, 2, 3];
const reversedArray = originalArray.toReversed();
console.log(originalArray); // [1, 2, 3]
console.log(reversedArray); // [3, 2, 1]