How to reverse an array in Javascript without changing the original array?

How to reverse an array in Javascript without changing the original array?

You can use slice method to make a copy then use reverse method to reverse it like this:

 const originalArray = [1, 2, 3, 4];
 
 const reverseArray = array.slice().reverse();
 // reverseArray: [4, 3, 2, 1]


The slice() method returns the selected elements in an array, as a new array object (The original array will not be changed)
The reverse() reverses an array in place. The first array element becomes the last, and the last array element becomes the first.


© 2019 4codev

Created with love by Sil.