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);
2
  • 1
    Given that they reference the same array? Yes. Commented Jan 28, 2015 at 19:02
  • That doesn't look like an array if it has an .airfares property. Commented Jan 28, 2015 at 19:05

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.