js delete object reference from two arrays

Viewed 229

When the same object reference exists in two arrays, the objects are equivalent, and updating one affects the other.

However deleting the object from one array does not delete it in the other.

Why not?

var a1 = [
  {i: 0, s: 'zero'}, 
  {i: 1, s: 'one'}
];

var a2 = [
  a1[0],
  a1[1]
];

// items point to same reference
print(a1[0] === a2[0]); // true (equivalent)

// updating one affects both
a1[0].s += ' updated';
print(a1[0] === a2[0]); // true (still equivalent)
print(a1[0]); // {"i":0,"s":"zero updated"}
print(a2[0]); // {"i":0,"s":"zero updated"}

// however, deleting one does not affect the other
delete a1[0];
print(a1[0]); // undefined
print(a2[0]); // {"i": 0, "s": "zero"}

Interestingly, deleting a property from one, does affect the other.

delete a1[1].s;
print(a1[1]); // {"i":1}
print(a2[1]); // {"i":1}

https://jsfiddle.net/kevincollins/4j6hj2v7/3/

2 Answers
Related