selection.filter()

selection.filter(filter)

Filters the selection, returning a new selection that contains only the elements for which the specified filter is true. The filter may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element.

For example, to filter a selection of table rows to contain only even rows:

var even = d3.selectAll("tr").filter(":nth-child(even)");

This is approximately equivalent to using d3.selectAll directly, although the indexes may be different:

var even = d3.selectAll("tr:nth-child(even)");

Similarly, using a function:

var even = d3.selectAll("tr").filter(function(d, i) { return i & 1; });

Or using selection.select:

var even = d3.selectAll("tr").select(function(d, i) { return i & 1 ? this : null; });

Note that the :nth-child pseudo-class is a one-based index rather than a zero-based index. Also, the above filter functions do not have precisely the same meaning as :nth-child; they rely on the selection index rather than the number of preceding sibling elements in the DOM.

The returned filtered selection preserves the parents of this selection, but like array.filter, it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed.

doc_D3_Js
2016-11-24 10:28:54
Comments
Leave a Comment

Please login to continue.