How to Reverse an Array In-Place and Out-of-Place in JavaScript
I remember that I used to Google this question quite a bit because it would come up repeatedly during work. Let’s take this time to understand and remember how JavaScript handles its reversals.
In-Place Reversal: reverse()
const arr1 = [1, 2, 3];
const arr2 = arr1.reverse();
console.log(arr1); // [ 3, 2, 1 ]
console.log(arr2); // [ 3, 2, 1 ]
Using reverse()
by itself will mutate, or modify, the original array.
Out-of-Place Reversal: slice()
and reverse()
const arr1 = [1, 2, 3];
const arr2 = arr1.slice().reverse();
console.log(arr1); // [ 1, 2, 3 ]
console.log(arr2); // [ 3, 2, 1 ]
Using slice()
with no arguments will default to slice(0)
, which returns the array from element 0
to the end of the array.
In other words, slice()
returns a copy of the array while reverse()
mutates the copied array.
Out-of-Place Reversal: slice()
and reverse()
const arr1 = [1, 2, 3];
const arr2 = arr1.slice().reverse();
Using slice()
with no arguments will default to slice(0)
, which returns the array from element 0
to the end of the array.
In other words, slice()
returns a copy of the array while reverse()
mutates the copied array.
Out-of-Place Reversal: spread
and reverse()
const arr1 = [1, 2, 3];
const arr2 = [...arr1].reverse();
In ES6, we can use the spread operator to create a new array that we eventually reverse. The general idea is the same as the method above.
Out-of-Place Reversal: reduceRight()
const arr1 = [1, 2, 3];
const arr2 = arr1.reduceRight((acc, value) => {
return [...acc, value];
}, []);
We use reduceRight()
to apply a function to some accumulator acc
and each value
of an array, from right to left.
Out-of-Place Reversal: Recursion
const reverse = ([head, ...tail]) => {
if (tail.length === 0) return [head];
else return [...reverse(tail), head];
};
const arr1 = [1, 2, 3];
const arr2 = reverse(arr1);
Out-of-Place Reversal: Good ol' for
loop
const arr1 = [1, 2, 3];
let arr2 = [];
for (let i = arr1.length - 1; i >= 0; i--) {
arr2.push(arr1[i]);
}