How to isolate a nested selection to update the data within?

Hi All,
I am sorry for the bad title, I wasn’t quite sure on how to write it as understandable as possible.
I have this grouped bar Chart mostly adapted from Mike Bostocks example.

I would like to isolate the rectangleGroups to move them into an update function.
But when I do something like
rectangleGroups = g.append("g") and later call the functions on rectangle Groups it doesn’t work.
Neither does using just the selection, i.e. rectangleGroups = g.selectAll()

If I leave it as is, the problem is that each time the data updates, new bars and groups get appended and the old ones are not removed.

How do I go about this correctly?

Thanks a lot in advance.
edit: Ok, I kinda found a workaround, its likely bad practice, but I just select all bars in the line above and do .remove().

2 Likes