Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate a JavaScript array passed to a function without changing the original argument array?

I would like to work with an array passed to a function while leaving the original array untouched. Here is a simple example of the problem.

function whyDoesArrChange(arr) {
   var newArr = arr;
   newArr.push(4);

   return arr;
 }
 
 console.log(whyDoesArrChange([1,2,3]));
// OUT: [1,2,3,4]

I would like only newArr to be changed, but the arr (from the arguments) returns the pushed value as well (returns [1,2,3,4]). How can I avoid this?

like image 460
user1486510 Avatar asked Aug 31 '25 16:08

user1486510


2 Answers

When passing an array to a function, the value of that array is a reference, you have to clone it to break the reference.

There are multiple ways to achieve this:

1 - Using .slice();

var newArr = arr.slice();

2 - Using .concat

var newArr = arr.concat([]);

3 - Using JSON.parse & JSON.stringify

var newArr = JSON.parse(JSON.stringify(arr));

You can check more ways and see how they perform in this jsperf I found.

like image 55
Marcos Casagrande Avatar answered Sep 02 '25 05:09

Marcos Casagrande


While Marcos' answer is correct, no doubt. There are more pure Array functions that can be used (A pure function is a function that doesn't alter data outside of its' scope).

Usually, if you'd like to do multiple actions on the array, I would go with Marcos' answer and then do those changes as usual. But when that's not the case, the following information may be useful:

  1. Adding: arr.concat([1]);
  2. Subarray (i to j): arr.slice(i, j + 1);
  3. Removing (i to j): arr.slice(0, i).concat(arr.slice(j + 1));

Also, filter and map are pure function that will not alter the array.

like image 28
Gershon Papi Avatar answered Sep 02 '25 04:09

Gershon Papi