Belal Othman Belal Othman - 4 months ago 7
Javascript Question

I have two arrays, I want to push some element from Ar1 to Ar2 and keep the references

I need to use two javascript arrays with angularjs.
I want to push some element from Ar1 to Ar2 and after that if I change the values of these elements in Ar2, I want the values in Ar1 to be changed automatically.

Answer

You can't do that. There is no link between the values that are in one array and the same values in another array. E.g.:

var a1 = [42];
var a2 = [];
a2.push(a1[0]);

...gives us this structure in memory:

       +---------+
a1---->| (array) |
       +---------+   
       | 0: 42   |
       +---------+

       +---------+
a2---->| (array) |
       +---------+   
       | 0: 42   |
       +---------+

There is no link between the 42 in a1 and the 42 in a2.

One alternative would be for both arrays to have references to objects, and use properties on those objects rather than entries contained in the arrays. Since both arrays would refer to the same objects, changes through the reference in one array would (of course) be accessible through the reference in the other array.

E.g.:

var a1 = [{foo:"bar"}];
var a2 = [];
a2.push(a1[0]);
console.log(a1[0].foo); // "bar"
a2[0].foo = "updated";
console.log(a1[0].foo); // "updated"

That works because this code:

var a1 = [{foo:"bar"}];
var a2 = [];
a2.push(a1[0]);

sets up this structure in memory:

       +------------+
a1---->|  (array)   |
       +------------+   
       | 0: ref5542 |----+
       +------------+    |
                         |     +------------+
       +------------+    +---->|  (object)  |
a2---->|  (array)   |    |     +------------+
       +------------+    |     | foo: "bar" |
       | 0: ref5542 |----+     +------------+
       +------------+    

Both arrays have references to the same object, so changing that object's state shows up regardless of how you look up the object.

Comments