Take a look at this code snippet on JSFiddle: https://jsfiddle.net/reko91/998woow6/
The issue I am facing with my project is that every time I add an element to an array, it ends up overwriting all the existing elements with the newly added one.
To replicate the problem, follow these steps:
Click on the
AddToArray
button, which adds the current values ofnodes
andedges
into an object and then pushes that object into thethisArray
array.Next, click on either
DeleteNodes
orDeleteEdges
to remove the last element from their respective arrays.Finally, press the
AddToArray
button again to add the updatednodes
andedges
into a new object, but you'll notice that the original object (at index 0) gets replaced by this new object.
I've tried researching online and suspect that closures might be causing this issue, but I'm unable to resolve it yet.
If you prefer viewing the code here, here it is:
var thisArray = [];
var nodes = [1, 2, 3, 4, 5];
var edges = [1, 2, 3, 4, 5];
function addToArray() {
var thisData = {
nodes: nodes,
edges: edges
}
thisArray.push(thisData)
console.log('thisArray')
console.log(thisArray)
}
function deleteNodes() {
nodes.pop();
console.log(nodes)
}
function deleteEdges() {
edges.pop();
console.log(edges)
}
<button onclick='addToArray()'>
AddToArray
</button>
<button onclick='deleteNodes()'>
Delete Nodes
</button>
<button onclick='deleteEdges()'>
Delete Edges
</button>