33

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?

2 Answers 2

71

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")
Sign up to request clarification or add additional context in comments.

Comments

-1

In your example, you want to add something depending on a condition or add nothing else. However, if you want to add something but it depends on a condition what you append, then you can use the fact that most values in D3 can be passed by constants and functions. This also applies to the function .append( ... ).

So if you want to append something but the type of DOM node you want to append depends on a condition, you can use something like the following:

d3.select("body").selectAll("div")
    .data([4, 8, 15, 16, 23, 42])
        .enter().append((d) => document.createElementNS("http://www.w3.org/2000/svg",
            d < 10 ? "rect" : "circle"))
            .text(function(d) { return d; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.