To reverse an array without mutating the original array in JavaScript. First, we can use the slice()
method on the array to create a copy of the array and then use the reverse()
method on that array to reverse the elements or items in the array.
/* Copy and Reverse the Array */
const reverseArr = arr.slice().reverse();
Suppose I have an array of numbers like this,
// array of numbers
const numsArr = [1, 2, 3, 4, 5];
First, let's make a copy of the array using the slice()
method on the array.
- If nothing is provided as an argument to the
slice()
array method, it copies the entire array and then returns a new array.
// array of numbers
const numsArr = [1, 2, 3, 4, 5];
// copy array using slice() method
const copyArr = numsArr.slice();
After that we can use the reverse()
method on the copied array to reverse the elements.
- The
reverse()
array method returns a new array with elements reversed.
// array of numbers
const numsArr = [1, 2, 3, 4, 5];
// copy array using slice() method
const copyArr = numsArr.slice();
// reverse the copied array
// using the reverse() method
const reverseArr = copyArr.reverse();
console.log(reverseArr); // Reversed array: [5, 4, 3, 2, 1]
console.log(numsArr); // Original array: [1, 2, 3, 4, 5]
Yes! 🔥.
We have successfully reversed our array without mutating the original array.
See this example live in JSBin.