EN
JavaScript - reverse array without mutating original array
0
points
In this article, we would like to show you how to reverse an array without mutating the original array in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
var arrayCopy = array.slice().reverse();
console.log(arrayCopy); // [ 'c', 'b', 'a' ]
Explanation:
In the example above the
slice()method returns a shallow copy of thearray. Thereverse()method reverses the copy of thearrayand saves the result inarrayCopy.