Oops. That is indeed not the case. Looking at the code history, the
filter method has always behaved that way, though there is a
long-standing comment (question) mentioning this behavior:
// TODO preserve null elements to maintain index?
It looks like I was confused when I wrote the documentation for this
particular method.
> Since I'm depending on a preserved index to determine positioning of
> the current element, this poses a bit of a problem.
You can do the equivalent thing using select. So, if this was your filter:
selection.filter(function(d) { return d > 42; })
Instead say:
selection.select(function(d) { return d > 42 ? this : null; })
> So what's the skinny on filter()? It seems like it's somehow not a
> first-class selection method (or that other selection methods aren't
> returning true selections.)
You likely encountered a different issue, which is that the enter
selection is not a first-class selection: it contains placeholder
nodes. The enter selection therefore does not support the full array
of operators, including filter.
https://github.com/mbostock/d3/blob/master/src/core/selection-enter.js
I expect we could add filter to the enter selection prototype, though.
But certainly not operators such as attr, and I don't think data would
make sense either.
Mike
Brilliant, that worked swimmingly. I was going to suggest adding that to the wiki, but I just noted that you're way ahead of me on that front. This is a decent example of using a function with select().
> You likely encountered a different issue, which is that the enter
> selection is not a first-class selection: it contains placeholder
> nodes. The enter selection therefore does not support the full array
> of operators, including filter.
> [...]
> I expect we could add filter to the enter selection prototype, though.
> But certainly not operators such as attr, and I don't think data would
> make sense either.
The biggest issue in my mind would be to make the special cases clear in the docs. E.g. if a selection method returns nodes with a restricted signature, perhaps annotate that in the docs, ala "enter() returns placeholder nodes which support only the following selection methods: X, Y, Z. If you need to call other methods <example>."
Thanks for your work on d3, Mike. I haven't had this much fun getting into a new framework in ages!
-- John