Personally I’d have this return a map instead of an object, so that the keys aren’t forced to be strings. Otherwise seems like a reasonable API, very similar to groupBy in any other moderately functional language, except with the “keys must be strings” restriction inherited from returning a plain object.<p>Also, for those thinking JS objects can have non-string keys, they can’t, it just sometimes appears that way due to JS type coercion: <a href="https://www.becomebetterprogrammer.com/can-javasscript-object-keys-be-numbers-or-non-string-values/" rel="nofollow">https://www.becomebetterprogrammer.com/can-javasscript-objec...</a><p>Edit: as pointed out by shawnz, this isn’t entirely accurate, JS object keys can also be symbols.
Unfortunately the typescript definitions for these two methods haven't been written yet [1].<p>[1] <a href="https://github.com/microsoft/TypeScript/issues/47171" rel="nofollow">https://github.com/microsoft/TypeScript/issues/47171</a>
Great - lodash needed a little less now.<p>Though I do often see people using a combination of maps, filters, reduces, lodash functions etc. one by one, rather than doing everything in a single for in loop. In most cases it feels that For In is still the most performant option, as you want to manipulate the data in more ways than just grouping
For what it's worth, the Laravel PHP framework (no affiliation) has the best introduction to higher-order methods for imperative programmers used to Javascript/C style of anything that I've come across:<p><a href="https://laravel.com/docs/master/collections" rel="nofollow">https://laravel.com/docs/master/collections</a><p>Most of these methods are also available as part of the Eloquent ORM, for filtering/reshaping queries before they're executed:<p><a href="https://laravel.com/docs/master/eloquent" rel="nofollow">https://laravel.com/docs/master/eloquent</a><p>Since being exposed to this way of working, I rarely use foreach() anymore, much less for(). The main downside being that I find most other languages tedious to work in now. LINQ in .NET/C# is nice, there might be others.
Hardly shorter than just writing the for loop, i.e. the example in python<p><pre><code> groupByAge = collections.defaultdict(list)
for person in people:
groupByAge[person["age"]].append(person)</code></pre>
I was just doing something like this and thinking “I do this in SQL all the time but users like to change things up so much it should be a native array thing.”
I worked on a Ruby gem to add group_by and aggregate_by functions to collections/enumerables. I finished about 1/2 of the functionality and found the implementation to be hateful and thought it would be received poorly. Now seeing this I am second guessing myself.