Skip to content Skip to sidebar Skip to footer

Removing Duplicate Edges From An Array For A D3 Force Directed Graph

I have an array of edges for a force directed graph, which looks like this but much longer. var rawLinks = [{ source: 1, target: 2 }, { source: 2, target: 1 },

Solution 1:

Since it doesn't matter who is the source and who is the target ("1 to 2" is the same of "2 to 1" in your problem), we'll first reorganize the array:

rawLinks.forEach(function(d){
    var sourceTemp = d.source, targetTemp = d.target;
    if(d.source > d.target){
        d.source = targetTemp;
        d.target = sourceTemp;
    }
});

That creates duplicates, like this:

{ source:1, target:2 }
{ source:1, target:2 }    

Then, we remove the duplicates:

function removeDups(myArray){
    myArray.sort();
    for(var i = 1; i < myArray.length; ){
        if(myArray[i-1].source === myArray[i].source 
           && myArray[i-1].target === myArray[i].target){
            myArray.splice(i, 1);
        } else {
            i++;
        }
    }
    return myArray;
}

Here is a demo:

var rawLinks = [{ source: 1, target: 2 },
    { source: 2, target: 1 },
    { source: 6, target: 7 },
    { source: 7, target: 6 },
    { source: 8, target: 9 },
    { source: 8, target: 9 },
    { source: 8, target: 86 },
    { source: 8, target: 101 },
    { source: 8, target: 133 },
    { source: 8, target: 134 }];
									
rawLinks.forEach(function(d){
	var sourceTemp = d.source; targetTemp = d.target;
	if(d.source > d.target){
		d.source = targetTemp;
		d.target = sourceTemp;
	}
});

functionremoveDups(myArray){
    myArray.sort();
    for(var i = 1; i < myArray.length; ){
        if(myArray[i-1].source === myArray[i].source && myArray[i-1].target === myArray[i].target){
            myArray.splice(i, 1);
            } else {
            i++;
            }
        }
    return myArray;
    }  

removeDups(rawLinks);

console.log(rawLinks);

Post a Comment for "Removing Duplicate Edges From An Array For A D3 Force Directed Graph"