1

The following filter is the same, but it result applied for two different element:

mNode.filter(function(otherNode) {
    return connectedNodes.indexOf(otherNode.id) > -1
}).select("image").style("opacity", BACKGROUND_OPACITY);

mNode.filter(function (otherNode) {
    return connectedNodes.indexOf(otherNode.id) > -1;
}).select("circle").style("stroke", "#f6f6f6");

how can I combine it to one filter without duplicate the code?

second, is there a way to apply to opposite more efficient?

mNode.filter(function(otherNode) {
     return connectedNodes.indexOf(otherNode.id) > -1
}).select("image").style("opacity", BACKGROUND_OPACITY);
mNode.filter(function(otherNode) {
      return connectedNodes.indexOf(otherNode.id) == -1
}).select("image").style("opacity", DEFAULT_OPACITY);

Like if the condition is satisfied apply 1st style otherwise apply the 2nd style.

Thanks!

2
  • Use for to iterate over mNode, inside it, use if...else and apply styles. Commented Dec 21, 2017 at 6:41
  • @Tushar that mNode is not an array and that filter is not Array.prototype.filter, that's a different method with the same name (that's confusing, I know...). So, the for won't work here. Commented Dec 21, 2017 at 7:58

1 Answer 1

1

Answering your first question: just use a selection:

var filtered = mNode.filter(function(otherNode) {
    return connectedNodes.indexOf(otherNode.id) > -1
});

And then:

filtered.select("image").style("opacity", BACKGROUND_OPACITY);
filtered.select("circle").style("stroke", "#f6f6f6");

Your second question is a bit more complicated, and has different solutions. I'd use an each to check every node. Something like:

mNode.each(function(d) {
  if (connectedNodes.indexOf(d.id) > -1) {
    d3.select(this).select("image").style("opacity", BACKGROUND_OPACITY);
  } else {
    d3.select(this).select("image").style("opacity", DEFAULT_OPACITY);
  }
})

However, I'd say that, intuitively, your code is faster than the each. You can always test both solutions using tools like jsPerf.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to work with 'each', but then I don't know how to apply the style on the node (from it's id)
It is d3.select(this).style(etc...)

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.