1

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);
seb
  • 313
  • 1
  • 7
  • 19

4 Answers4

9

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>
ssube
  • 47,010
  • 7
  • 103
  • 140
1

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.

huderlem
  • 251
  • 1
  • 5
1

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);
Morgen
  • 1,010
  • 1
  • 11
  • 15
1

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);
A.B
  • 20,110
  • 3
  • 37
  • 71