seb
seb

Reputation: 313

Splice temporary array will modify the main array

Is it normal that when I use splice on temp, mainArray is also modified ?

console.log(mainArray);

var temp = mainArray;

temp.airfares.splice(index, 1);

Upvotes: 1

Views: 6449

Answers (4)

A.B
A.B

Reputation: 20445

Arrays are stored as an reference not actual array is stored. An reference of it is stored (Since arrays are also object)

Here you can use slice() or concat() method's hack to assign it without reference

 var temp = mainArray.slice();

or

 var temp = [].concat(mainArray);

Upvotes: 1

ssube
ssube

Reputation: 48247

This is because temp is not an entirely new array, just a reference to mainArray. You need to make a copy.

To easily make a copy of an array, using Array.prototype.slice() is common. Note that it will not copy each element, but will copy the array itself (so you can push or remove elements later).

For example:

var data = [1, 2, 3, 4, 5];
document.getElementById("original").textContent = JSON.stringify(data);

var ref = data;
var copy = data.slice();

// Add some values to data, ref will change but copy won't
data.push(6, 7, 8);

document.getElementById("ref").textContent = JSON.stringify(ref);
document.getElementById("copy").textContent = JSON.stringify(copy);
<pre id="original"></pre>
<pre id="ref"></pre>
<pre id="copy"></pre>

Upvotes: 9

Morgen
Morgen

Reputation: 1038

Yes, JavaScript arrays are objects, so temp and mainArray are both references to the same underlying object.

You want something along the lines of this:

console.log(mainArray);
var temp = mainArray.slice();
temp.airfares.splice(index, 1);

Upvotes: 1

huderlem
huderlem

Reputation: 251

var temp = mainArray; will set temp as a reference to mainArray. That means, they both refer to the same array. Therefore, if you modify temp, you're also modifying mainArray.

Upvotes: 1

Related Questions