Paul Smith
Paul Smith

Reputation: 187

How to remove selected item from a list in d3

I am working with a d3 scatterplot and when I right click a dot a drop down menu menu appears. When I click an option (called "Remove from Library") I want to remove that selected item/dot from an array (libraryData). I am new to d3 so what makes sense to me is simply

libraryData.remove(d);

I know this isnt a function. I found something similar which was the array.splice() function. But I cant figure out how I apply that when I dont know the position of the item I want to remove in the array. This is where I define my function within the option of the menu:

{
title: 'Remove from Library',
action: function (elem, d, i) {

        d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) {

            libraryData.?????();
                console.log(libraryData);   
        })
    }

Any help is appreciated, as you can tell I am new to d3!

Upvotes: 0

Views: 1746

Answers (1)

thatOneGuy
thatOneGuy

Reputation: 10612

You're kind of on the right track with remove(d).

You can use this :

d3.select(selectedElement).remove();

So like the example below if you want to remove the element with ID of 'elephant' it will be like so :

nodes.each(function(d){
  if(d.id ==='elephant'){
    d3.select(this).remove();
  }
}

That is if you have the ID in the dataset. You can use anything in this check.

Or even simpler, if you know the ID is elephant it would be :

d3.select('#elephant').remove();

Or say you have an array of data and you just splice your array at the correct index.

For example :

Say you have some data and you want to remove the data with id of 'elephant';

Loop through and remove element with id=elephant

for(i=0;i<data.length;i++){
  if(data[i].id === 'elephant'){
    data.splice(i--,1);
  }
}

Notice I use i--. This is to update the array otherwise if you want to remove multiple elements you will get the wrong index.

Then once you splice it just update your visualization.

Upvotes: 1

Related Questions