I'm writing a d3 force graph
to make the update look fliud I implemented it like the Modifying a Force Layout example. But unline in the example I want a dynamic updating behaviour. Given the situation I already called initializeGraphData(json);
once, my nodes
- array contains a set of node
objects. On 2nd call I push every json.nodes
object to the nodes
- array. Then I get the difference between the nodes
- array and the json.nodes
- array. For each different object I want to remove it from the nodes
array by giving in it's index and the parameter 1
to remove only one element.
function initializeGraphData(json){
json.nodes.forEach(function(node){
nodes.push(node);
});
json.links.forEach(function(link){
links.push(link);
});
var difInNodes = nodes.diff(json.nodes);
difInNodes.forEach(function(node){
nodes.slice(nodes.indexOf(node), 1);
});
var difInLinks = links.diff(json.links);
difInLinks.forEach(function(link){
links.slice(links.indexOf(link), 1);
});
nodes.forEach(function(node){
java.alert("In nodes array: " + node.name);
});
draw();
checkForLinked(json);
checkForOptions(json);
}
One node element might look like this
{"img":"ron.png","concept":null,"name":"Ron Weasley","id":1,"shortname":"Ron","properties":[{"property":"Animal","value":"Rat"}],"group":"#867b69"}
I do know that these are not the same objects when I try to remove them, so I thought I could use the node.id
property, which didn't work as well.
var difInNodes = nodes.diff(json.nodes);
difInNodes.forEach(function(node){
nodes.slice(node.id, 1);
});
How can I remove an object in an array that is equivalent by content to one in another array 1:1?
slice
doesn't remove entries from the array, it creates a new array with a subset of the entries from the original.
Given where and how you're using it, I believe you meant to use splice
(with a p
).
But you're also using node.id
as though it were the index of the entry, which isn't likely to be correct (and certainly won't be correct after the first time you change the array). So first you need to find the right index, then use splice
to remove the entry. ES2015 adds findIndex
to the Array.prototype
which is useful for finding the index of an entry based on a callback function; it can be shimmed/polyfilled on ES5 and earlier engines.
So:
var difInNodes = nodes.diff(json.nodes);
difInNodes.forEach(function(node){
var index = nodes.findIndex(function(entry) { return entry.id == node.id; });
if (index !== -1) {
nodes.splice(node.id, 1);
// ^
}
});
Alternately, you could use Array#filter
to build a new array each time with only the entries you want:
var difInNodes = nodes.diff(json.nodes);
difInNodes.forEach(function(node){
nodes = nodes.filter(function(entry) { return entry.id != node.id; });
});
Which you use is up to you, largely depending on what else will have a reference to the array (since the second method creates a new array).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments