The reverse() method reverses the order of the elements in an array but it mutates the original array. Let's take a simple example to demonistrate this case,
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reverse();
console.log(newArray);
console.log(originalArray);
There are few solutions that won't mutate the original array. Let's take a look.
- Using slice and reverse methods:
In this case, just invoke the
slice() method on the array to create a shallow copy followed by reverse() method call on the copy.
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.slice().reverse();
console.log(originalArray);
console.log(newArray);
- Using spread and reverse methods:
In this case, let's use the spread syntax (...) to create a copy of the array followed by
reverse() method call on the copy.
const originalArray = [1, 2, 3, 4, 5];
const newArray = [...originalArray].reverse();
console.log(originalArray);
console.log(newArray);
- Using reduce and spread methods:
Here execute a reducer function on an array elements and append the accumulated array on right side using spread syntax
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduce((accumulator, value) => {
return [value, ...accumulator];
}, []);
console.log(originalArray);
console.log(newArray);
- Using reduceRight and spread methods:
Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and append the accumulated array on left side using spread syntax
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduceRight((accumulator, value) => {
return [...accumulator, value];
}, []);
console.log(originalArray);
console.log(newArray);
- Using reduceRight and push methods:
Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and push the iterated value to the accumulator
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduceRight((accumulator, value) => {
accumulator.push(value);
return accumulator;
}, []);
console.log(originalArray);
console.log(newArray);