var System = [[1, 3, 5]];
var Agents = [];
Agents.push([0, [0]]);
var AgentLocation = Agents[0][0];
var AgentPath = Agents[0][1];
console.log(Agents);
Agents.push([1, AgentPath]);
console.log(Agents);
Agents[1][1].push(System[AgentLocation][0]);
console.log(Agents);
At the end of this code, before I log in Agents, I pushed one array with the number 1.
Why does both items have the numeber 1 pushed?
If you were to run this, you would be able to see that the array:
[
[ // First Item
0,
[0]
],
[ // Second Item
1,
[0] // Second Item
]
]
At Agents[1][1], which is the second item of the second item, which should mean that the value of second of the second item should be different from the second of the first item, right? Right?
What did I do wrong?
As you can see, System[AgentLocation][0] translates to 1. But when I replace it with one, it suddenly works normally.
Same with all the other parts where I didn’t just replace it with numbers.
The expected result is:
[
[
0,
[0]
],
[
1,
[0, 1]
]
]
>Solution :
The is because both Agents[0][1] and Agents[1][1] are referencing the same array (AgentPath). This means that any modifications made to AgentPath will be reflected in both locations, since they both point to the same array in memory.
So, when you push the value System[AgentLocation][0] (which is 1) onto Agents[1][1], you are also pushing that same value onto Agents[0][1], since they both reference the same array.
To avoid this issue, you could create a new array for AgentPath when you push it onto Agents[1], like this:
var System = [[1, 3, 5]];
var Agents = [];
Agents.push([0, [0]]);
var AgentLocation = Agents[0][0];
var AgentPath = Agents[0][1];
//console.log(Agents);
Agents.push([1, AgentPath.slice()]); // create a new array for AgentPath
//console.log(Agents);
Agents[1][1].push(System[AgentLocation][0]);
console.log(Agents);
![[[0, [/id:3/0, 1]], [1, /ref:3/]]](https://i0.wp.com/i.stack.imgur.com/F2JOf.png?w=1200&ssl=1)