<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>General Update Pattern</title>
    <script src="https://d3js.org/d3.v7.js"></script>
  </head>

  <body>

    <script>

// Create svg and initial bars

const svg = d3.select("body")
  .append("svg")
    .attr("width", "500")
    .attr("height", "400");

const bardata = [300, 100, 150, 225, 75, 275];

const bars = svg.selectAll("rect")
  .data(bardata);

bars.enter().append("rect")
  .attr("x", "30")
  .attr("y", (d, i) => i*50)
  .attr("width", d => d)
  .attr("height", "35")
  .attr("fill", "lightgreen");

// General Update Pattern

function update(data) {

  const bars = svg.selectAll("rect")    // data join
    .data(data);

    bars.enter()
      .append("rect")    // add new elements
        .attr("x", "30")
        .attr("y", (d, i) => i*50)
        .attr("width", d => d)
        .attr("height", "35")
        .attr("fill", "yellow")
      .merge(bars)    // merge
        .transition()
        .duration(2000)
        .attr("width", d => d)
        .attr("fill", "orange");

    bars.exit().remove();    // remove extra elements
    }

    </script>

  </body>

</html>