Derick Kolln
Derick Kolln

Reputation: 633

Filter out nodes by the radius size

I use D3.js and I am able to filter out nodes by their "fill" attribute(in this case the color red) with the help of this code:

node.filter(function() {
    return d3.select(this).attr("fill") === "red"
})

Now, my next goal is to filter them out by their radius, that means the "r" attribute like you can see below. Unfortunally the code does not filter them out. Is there someone who could help me maybe? Thanks so much!

node.filter(function() {
    // return d3.select(this).attr("fill") === "red"
    return d3.select(this).attr("r") === 12
})

Upvotes: 1

Views: 136

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

Your problem here is the strict equality:

return d3.select(this).attr("r") === 12
    //strict equality here--------^  ^--- this is a number

You are comparing the result of the getter attr("r") with a number. However, attr("r") returns a string, not a number.

The reason for that is easy to understand if you have a look at the source code: the getter uses getAttributeNS, which:

returns the string value of the attribute with the specified namespace and name. (emphasis mine)

Therefore, using the strict equality, you have "12" === 12, and that returns false.

Solution:

Use the equality (==) operator instead or, alternatively, compare with a string:

return d3.select(this).attr("r") === "12"
    //this is a string ---------------^

Here is a simple demo. I'm filtering the circles with 12px radii...

var filteredCircles = circles.filter(function() {
    return d3.select(this).attr("r") === "12"
}).attr("fill", "red")

... and painting them red. Check it:

var data = d3.range(9);
var svg = d3.select("svg");
var circles = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 50)
  .attr("cx", function(d) {
    return 10 + 30 * d
  })
  .attr("r", function(d) {
    return d % 2 ? 12 : 8
  })
  .attr("fill", "teal");

var filteredCircles = circles.filter(function() {
  return d3.select(this).attr("r") === "12"
}).attr("fill", "red")
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Upvotes: 3

Related Questions