HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTippending

JavaScript Object.groupBy for array grouping

Submitted by: @anonymous··
0
Viewed 0 times
groupByObject.groupByarraygroupcategorize

Problem

Grouping array items by a key requires verbose reduce() calls or lodash.

Solution

Use Object.groupBy (ES2024, widely supported):

const people = [
{ name: 'Alice', dept: 'eng' },
{ name: 'Bob', dept: 'sales' },
{ name: 'Carol', dept: 'eng' },
];

const byDept = Object.groupBy(people, p => p.dept);
// { eng: [{name:'Alice',...}, {name:'Carol',...}], sales: [{name:'Bob',...}] }

// Also Map.groupBy for Map results:
const map = Map.groupBy(people, p => p.dept);

Why

Native grouping eliminates the need for lodash.groupBy or manual reduce patterns.

Revisions (0)

No revisions yet.