Do I understand it wrong? or it is supposed to be that way?
Original circle
d3.select("svg").selectAll('circle')
.data([{'name':'john', 'age': '50'}]).enter().append('circle')
.attr("cx", function(d){return d.age;}).attr("cy", '200').attr("r", '10').attr("fill", 'red');
on click buttonA called below function
function prependValue(){
d3.select("svg").selectAll('circle')
.data([{'name':'peter', 'age': '100'}, {'name':'john', 'age': '50'} ])
.enter().append('circle').attr("cx", function(d){return d.age;}).attr("cy", '200').attr("r", '10').attr("fill", 'green');
}
I’m supposing it should add a green circle at cx = 100 for peter, however, it change the color of the circle for john to green.
If i do
.data([{'name':'john', 'age': '50'}, {'name':'peter', 'age': '100'} ])
everything works as expected.
If you don’t specify a function to use for matching data elements (the optional argument to
.data()), D3 matches elements by their index. That is, it indeed assumes that you will pass elements in the same order.To prevent this, pass in a function that tells it how to match elements (e.g. by name). See the documentation for more information.