Sunday, December 29, 2024

How to Reverse an Array Without Mutating the Original Array

 

The reverse() method in JavaScript reverses the order of elements in an array. However, it mutates the original array, which may not always be desirable. For example:

const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reverse();
console.log(newArray); // [5, 4, 3, 2, 1]
console.log(originalArray); // [5, 4, 3, 2, 1]

To avoid mutating the original array, here are a few alternative solutions:

1. Using slice() and reverse()

Create a shallow copy of the array using the slice() method and then reverse the copy.

const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.slice().reverse();
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [5, 4, 3, 2, 1]

2. Using Spread Syntax (...) and reverse()

Use the spread operator to create a copy of the array and then reverse it.

const originalArray = [1, 2, 3, 4, 5];
const newArray = [...originalArray].reverse();
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [5, 4, 3, 2, 1]

3. Using reduce() and Spread Syntax

Use the reduce() method to accumulate a reversed array by prepending each element.

const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduce((accumulator, value) => {
  return [value, ...accumulator];
}, []);
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [5, 4, 3, 2, 1]

4. Using reduceRight() and Spread Syntax

The reduceRight() method processes array elements from right to left. Use it to accumulate a reversed array by appending each element.

const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduceRight((accumulator, value) => {
  return [...accumulator, value];
}, []);
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [5, 4, 3, 2, 1]

5. Using reduceRight() and push()

Similar to the previous approach, but this time, use the push() method to add elements to the accumulated array.

const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduceRight((accumulator, value) => {
  accumulator.push(value);
  return accumulator;
}, []);
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [5, 4, 3, 2, 1]

These methods allow you to reverse an array without altering the original, preserving its state for further use. Choose the one that best fits your use case and coding style.

No comments:

Post a Comment

Understanding unshift and shift Methods in JavaScript

JavaScript is known for its robust array manipulation capabilities, offering various methods to add, remove, or transform elements. Two such...