That will soon no longer be needed since a native implementation has been introduced in the form of Array.prototype.groupBy. And it is in stage 3 now!
To start using it today, we can use the polyfill provided by core-js.
Let us assume we have the following array of objects:
And we want to group them by their age:
An example of grouping a simple array of numbers into odd and even numbers:
groupByToMap works exactly like the groupBy method, the only difference is that it returns a Map.
And that is it!
Note: The TypeScript definitions for these methods have not been written yet. Follow this issue for further updates on it.
That is as simple as it gets in terms of implementation and this should land in ES2022 soon and hopefully, the TypeScript definitions are done soon too.