You should make use of D3's data binding approach. Mike Bostock has great docs explaining how it works. First one is somewhat outdated but still explain things clearly.

Bind the basin array to the "map.legendBasin" selection and then when you update the basin array, you can just use the enter() selection to append the new elements.

You would do something like the following:

   .data(basin, function(d){return d;})//join using key
   .attr("x", 15)....//etc whatever stuff you want

Notice that this code is reusable for both the first time and when new elements come in. When the new array comes you can simply call this function again and only the new elements will get created as the key will match for the existing elements while it would not for the new elements hence the enter() selection will contain only the data not already appended as an element in the DOM. You may use the exit() selection in case you have to remove elements.

Related Query