score:1

Accepted answer

I know this might be a repetitive issue to answer but I still think it might be useful to a lot of developers who are new to d3. Also, the blog that I refer to here, is really very useful.

To overcome the usability issue from d3 v3, a new selection class merge was introduced.

Mark's words:

D3 4.0 removes the magic of enter.append. (In fact, D3 4.0 removes the distinction between enter and normal selections entirely: there is now only one class of selection.) In its place, a new selection.merge method can unify the enter and update selections:

You can read more on this here: d3 CHANGES#selection

Also, I came across this blog which I'd like to share: https://medium.com/@mbostock/what-makes-software-good-943557f8a488

In your example, using the same merge logic, here's the snippet:

var data = [
  {key: 1, values:[1, 2, 3]},
  {key: 2, values:[3, 4, 5]},
 ] 
function update(data) {
  var table = d3.select('#gogo')
  var tr = table.selectAll('tr')
    .data(data)

  var rowenter = tr.enter().append('tr')

  var td = tr.merge(rowenter).selectAll("td span")
    .data(d=>d.values )
    .text(d=>d)

  td.enter().append('td').append('span')
    .text(d=>d)
}
update(data)
ref()
function ref() {
  setInterval(()=>{
    data.map(item=> {
      for (var i=0; i<3; i++) {
        item.values[i] = Math.floor(Math.random() * 100) + 1
      }
    })
    update(data)
  }, 1000)
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<table id="gogo">

</table>

Hope this helps.


Related Query