How to create elements depending on data in D3?

d3.js, javascript

Solution

The simplest way is to filter your array before calling `.data( ... )`:

d3.select("body").selectAll("p")
    .data([4, 8, 15, 16, 23, 42].filter(function(d){ return d < 10; }))
  .enter().append("div")
    .text(function(d) { return d; });

will create a div only for 4 and 8.

Alternatively, you can filter your selection after binding your array to elements on the page to conditionally create children elements:

d3.select("body").selectAll("div")
    .data([4, 8, 15, 16, 23, 42])
  .enter().append("div")
    .text(function(d) { return d; })
 .filter(function(d){ return d == 8; }).append("span")
    .text("Equal to 8")

Problem

looking at sample: ``` d3.select("body").selectAll("div") .data([4, 8, 15, 16, 23, 42]) .enter().append("div") .text(function(d) { return d; }); ``` cant help but wonder how to make append sensitive to provided data - say `do append and fill text` with some predicate say `if d == 8` othervise do not append?

Original source