Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by MacKenzi Martin
To reverse an array without modifying the original, call the slice()
method
on the array to create a shallow copy and call the reverse()
method on the
copy, e.g. arr.slice().reverse()
. The reverse
method will not modify the
original array when used on the copy.
const arr = ['a', 'b', 'c']; const reversed1 = arr.slice().reverse(); console.log(reversed1); // 👉️ ['c', 'b', 'a'] console.log(arr); // 👉 ️['a', 'b', 'c']
The first step is to create a shallow copy of the array by using the Array.slice method.
const arr = ['a', 'b', 'c']; const copy = arr.slice(); console.log(copy); // 👉️ ['a', 'b', 'c']
slice
method is called without supplying any parameters, it returns a shallow copy of the original array.The last step is to use the Array.reverse method on the copied array.
The reverse()
method reverses the array in place and returns the result.
reverse()
method on a copy of the array.An alternative approach is to use the spread syntax (...).
To reverse an array without modifying the original:
reverse()
method on the copy.const arr = ['a', 'b', 'c']; const reversed2 = [...arr].reverse(); console.log(reversed2); // 👉️ ['c', 'b', 'a'] console.log(arr); // 👉 ️['a', 'b', 'c']
We used the spread syntax (...) to unpack the values of the array into a new array, creating a shallow copy.
This enables us to use the reverse()
method without modifying the original
array.
slice
method might be a little bit faster when dealing with large arrays.