I'm struggling with understanding the merge function in D3, despite reading through the D3 API countless times.
The API says: "This method is commonly used to merge the enter and update selections after a data-join. After modifying the entering and updating elements separately, you can merge the two selections and perform operations on both without duplicate code."
Here's an example of the supposedly straightforward use of it, in a force directed chart, where the ticked function is called with every tick:
var simulation = d3.forceSimulation(nodes)
.force("charge", chargeForce)
.force("center", centerForce)
.on("tick", ticked);
function ticked() {
var u = d3.select("svg").selectAll("circle").data(nodes)
u.enter().append("circle").attr("r",5)
.merge(u) // What is the merge function doing here?
.attr("cx", d => d.x)
.attr("cy", d => d.y)
u.exit().remove() // Why is it necessary to remove excess objects w/ the exit selection?
}
I understand how data-binding works, and how enter() and exit() selections work. However, I've never had to use a "merge" before, and I don't understand it is doing here. If someone could briefly walk through what is going on in this function step-by-step, that would be extremely useful. I'm sure others have similar questions.
merge()
does not concatenate selections. The API states that explicitly: "This method is not intended for concatenating arbitrary selections, however: if both this selection and the specified other selection have (non-null) elements at the same index, this selection’s element is returned in the merge and the other selection’s element is ignored.".