JavaScript gets Array grouping
For a couple of years I have been writing the same array map
, filter
, sort
and reduce
callback functions. Performing simple React state mutations and transforming that state into render-ready arrays and api-ready objects.
Most of those callbacks are pretty simple but grouping items by a condition is so convoluted that I've seen other developers reach for Lodash or a self rolled utility function.
I still prefer Array.prototype.reduce
in my private code for one simple and stupid reason:
"I have written this function so many times that I recognise it's shape."
const { true: pastMeetups, false: nextMeetups } = meetups
.reduce((groupedMeetups, meetup) => {
const group = isPast(meetup);
return {
...groupedMeetups,
[group]: [
...(groupedMeetups[group] ?? []),
meetup
]
};
}, {});
One project might use Lodash and another might use a self rolled utility function but I will always immediately recognise a properly indented 'group by condition'-reduce.
This is scanability by experience. Somebody who has seen and written this a few dozen times will recognise it but what about someone who comes across this construction for their first time?
I code differently for myself and for cooperation. Array grouping is one of the differences that I wouldn't give up on.
That's where I stood until I came across the Array grouping proposal. A standardised way to do array grouping, built into JavaScript.
This is what the same code looks like using array grouping.
const { true: pastMeetups, false: nextMeetups } = meetups.group(isPast)
const { true: pastMeetups, false: nextMeetups } = Object.groupBy(meetups, isPast)
This will get rid of one of the reasons to use lodash but also reduces the need for my 'recognisable' code shape.