Reverse An Array Without Modifying The Original In JavaScript

To reverse an array without modifying the original in JavaScript, you can use any of these methods –

  1. Use the arr.slice().reverse() method – This is the most straightforward and easy to understand method. It firstly slices the original array, then reverses the sliced array and finally returns it.
  2. Use the spread operator(…) with the Array.reverse() method – This is a newer feature and it can be used to reverse an array without modifying the original array.

Let’s look at each of these methods in detail below.

Reverse An Array Without Modifying The Original In JavaScript

reverse an array without modifying the original in javascript

Use The arr.slice().reverse() Method

This is the most straightforward and easy to understand method. When we call the Array.slice() method without any parameter, it creates a shallow copy of the original array.

When we call the Array.reverse() method on the shallow copy, the original array is not modified. Finally, we return the reversed array from the function.

Here is the code for this method –

function reverseArray(arr) {

  return arr.slice().reverse();

}

console.log(reverseArray([1, 2, 3])); //[3, 2, 1]

Use The Spread Operator (…) With The Array.reverse() Method

This is a newer feature and it can be used to reverse an array without modifying the original array.

The spread operator(…) allows us to split up the elements of an array into individual values.

When we call the Array.reverse() method on the individual values, they are reversed but the original array is not modified. Finally, we return the reversed array from the function.

Here is the code for this method –

function reverseArray(arr) {

  return [...arr].reverse();

}

console.log(reverseArray([1, 2, 3])); //[3, 2, 1]

Conclusion

In this article, we looked at how to reverse an array without modifying the original in JavaScript.

We saw that there are two ways to do this – using the arr.slice().reverse() method and using the spread operator(…) with the Array.reverse() method.

Both of these methods create a shallow copy of the array, reverse it and return it. The original array is not modified in either case.

Leave a Reply