How to reverse an array in JavaScript
To reverse an array in JavaScript, clone it with concat
and then reverse the clone with reverse
.
const myArray = [1, 2, 3];
const reversed = myArray.concat().reverse();
console.log(reversed);
// => [3, 2, 1]
If you want to reverse the array in place, don’t call concat
.
const myArray = [1, 2, 3];
myArray.reverse();
console.log(myArray);
// => [3, 2, 1]
That’s it!