New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
_.count method #702
Comments
Thanks for asking. This looks like a combo of a couple of existing methods. We'll keep an eye on the popularity of the request. |
👍 for I was surprised to find that these don't already exist! Wouldn't it be nice, when you just want to count something, to simply reach for the Of course you can do it with "filter/length" but that seems a tiny bit awkward, and counting is such a simple and fundamental concept -- it deserves it's own function. ( plus, there's the performance thing -- you could implement it without creating a new array ). |
My only conflict is how count is useful in applications -- I'm trying to think of times where I want how many satisfy a predicate and not which -- I keep coming to UI concerns only. Is there a meaningful algorithm or use case you can come up with that just wants to know how many and not which? Or rather, one such that you do not want the filtered set (either side)? Edit: _.sumBy(collection, (x) => pred(x) ? 1 : 0) |
@c-dante Oh neat! _.sumBy(collection, _.flow(pred, Boolean)); |
Just stumbled across this (because I need to count predicate-satisfying values); I'd like to add that |
I'm for a mixin of: _.count = _.sumBy(collection, _.flow(pred, Boolean)); Whether its implemented that way or not. It's pretty clear what would be expected from: _.count(myNumbers, x => x > 5); // I read this is, "how many of myNumbers are > 5
_.count(name.split(''), x => x === 'a'); // How many "a" are in name?
_.count(resturants, x => distanceFromMe(x) > 10mi); // How many resturants are within 10mi of my location |
There also is an argument of efficiency to make here. Most combined functions which achieve the behavior described in this ticket will build some kind of temporary object, which is then further evaluated for deriving the final count. Obvious examples are the filter+length and the map+sum approaches described above. A more efficient implementation would only require a single integer for counting. This ticket therefore has my vote, because bits are precious. |
I'd upvote this too. |
The predicate needs to return a number not a boolean, hence _.sumBy(collection, _.flow(pred, Number)); |
In a type-safe world, sure. But |
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Would it make sense for lodash to have a
_.count
method?Like this: http://ruby-doc.org/core-2.1.2/Enumerable.html#method-i-count
I'd be happy to implement one and submit a PR if this is appropriate.
The text was updated successfully, but these errors were encountered: