How To Reverse An Array Without Modifying The Original In JavaScript

Reverse an Array without Modifying the Original in JavaScript

There are many ways to reverse an array without modifying the original in JavaScript, including available methods in combination or using a separate sorting algorithm. Please read the following instructions to complete it.

Reverse an array without modifying the original in JavaScript

Use reverse() method

The reverse() is a built-in method in Javascript. After using this method, the output is an array of elements with a wholly reversed sorted order.

Syntax:

arr.reverse()

Parameter:

  • arr: is the desired reference input array.

Example:

// Array initialization
var originArr = [1, 2, 3, 4];

// Use the reverse() method to reverse
var reverseArr = originArr.reverse();

console.log(reverseArr);

Output

(4) [4, 3, 2, 1]

Here is the simplest example of using the reverse() method to reverse an array without modifying the original in JavaScript. And depending on the usage, the new user can keep the original array or not. The following case will always assign the result to the original array, saving memory.

// Array initialization
var originArr = [1, 2, 3, 4];

// Use the reverse() method to reverse
var originArr = originArr.reverse();

console.log(originArr);

Output

(4) [4, 3, 2, 1]

The result remains unchanged but saves an array variable corresponding to the original array.

Use for loop

In addition to the available method described above, we can use the loop to create our own sorting algorithm suitable for the problem requirements.

Example:

// Array initialization
let originArr = [1, 2, 3, true, 4, 5, 6, 7,'a'];
var reverseArr = []

// Get length of originArr
let n = originArr.length-1;

for(let i=0; i<=n/2; i++) {
  let temp = originArr[i];

  // Take the last element and put it first
  reverseArr[i] = originArr[n-i];
  reverseArr[n-i] = temp;
}

console.log(reverseArr);

The algorithm used in the above example is also quite simple, using a for loop to repeat the number of assignments corresponding to the original array size. Each iteration uses the intermediate variable temp to get the last element in the original array and assign it to the new array.

Output

(9) ['a', 7, 6, 5, 4, true, 3, 2, 1] 

Summary

The article has presented the two most basic ways to reverse an array without modifying the original in JavaScript, each with its application cases. If you want to save memory, always assign the original array to the position to be assigned. If you need to reuse the original array, initialize a new array. Thank you for reading.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *