Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js delete object reference from two arrays

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/

like image 872
Kevin Collins Avatar asked Aug 27 '26 09:08

Kevin Collins


1 Answers

To answer why last print(a2[0]); still shows value, lets start analyzing the code.

Your a1 is an array and when you initialize it with objects, it will create objects and store their reference.

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

This part, by your comments is clear, but what happens when you do delete a1[0]?

Will it remove the object? Answer is No. It will remove the property stored at 0th index in a1 and set it to undefined. But if you delete the property of the object held at that reference, it will show in both: sample

What happens to the object then? The value is retained and will be garbage collected if no one is referring it. In your case, since a2[0] still is accessing it, it will retain the value.

You can check following sample for reference.

like image 145
Rajesh Avatar answered Aug 29 '26 23:08

Rajesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!