The groupBy function is one of the functions why people use Lodash in their JavaScript code base. Here I want to give you a brief example on how to implement groupBy in vanilla JavaScript without Lodash by just using JavaScriptâs reduce method.
Letâs say we have the following array of objects and we want to group them by property (here color) to get the following output:
We can use JavaScriptâs reduce method on an array to iterate over every item:
We start with an empty object as our accumulator (here acc ) for this reduceâs callback function . For every iteration of the function, we return the changed (here still unchanged) accumulator. Letâs implement groupBy:
If the accumulator has no array initialized for the currently iterated valueâs color, we create an empty array for it allocated in the object whereas the color is the key. Afterward, we can assume that there is an array for the color and just push the value to it:
The groupBy in JavaScript is done. Here again with comments for both steps:
Essentially we start with an empty object and for every iterated value, we negotiate whether we need to allocate a new array based on the property (here color) in this object. Afterward, we push the value to the (new) array.