Sure, that is a good basic solution. Is it the best solution? That is subjective, but there is certainly a more efficient solution. Can you imagine a way to do this without sorting, making only one pass through the data?
Mildly related - Is there a performance impact/general preference between using a reduce vs a filter + length in JavaScript?
I know in some languages both approaches provide the same performance (Rust) while other languages produce less efficient code for filter + length (which is a shame because it looks cleaner/more readable).
I wouldn’t expect a difference, but it also may be engine dependent because I think the spec just specifies the behavior, not the implementation. And JS isn’t exactly a fast language anyway so I think most of the time you don’t worry micro-optimizations like this. Just my $.02.
There you go! If you are feeling up for a challenge, you can try to formulate that same logic using high order methods, with either a reduce or a filter + length.
Yeah, I mean it is very dependent on language. But to me that is semantically what reduce is for - reducing an array into a single value. I prefer the reduce, but I also wouldn’t kick your solution out of bed for eating crackers.
Yeah, it took me a while to get used to. I started writing those as reduces but soon saw that most codes used filter+count in that community. Weird how languages pick up quirks like that.
I’m a big fan of .reduce, but in this case, what could be more sexy than a solution that eliminates the necessity to sort the array first? I’m not sure how to do this purely with .reduce, without a chain .sort().reduce(). But then again I’m maybe just easily impressed by fancy one-liners like