Grouping Data with Object.groupby() (ES2024)
Quick Overview
`Object.groupBy()` buckets an array by whatever key the callback returns, replacing the usual `reduce` boilerplate. The result has a null prototype, so it carries no inherited methods to collide with keys.
Deep Dive
1. Native Data Grouping
ES2024 introduced Object.groupBy(), a native JavaScript method to group array elements according to category keys returned by a testing callback function.
2. Why It Matters
Previously, grouping array items required writing complex .reduce() accumulators. Object.groupBy() performs categorization natively in 1 clean line.
3. The Pattern
Pass an array and a callback function that returns the group category key string:
const inventory = [
{ name: "Apples", category: "Fruit" },
{ name: "Carrots", category: "Vegetable" },
{ name: "Bananas", category: "Fruit" },
];
// Group items natively by category
const grouped = Object.groupBy(inventory, (item) => item.category);
console.log(grouped.Fruit);
// Output: [{ name: "Apples", category: "Fruit" }, { name: "Bananas", category: "Fruit" }]
console.log(grouped.Vegetable);
// Output: [{ name: "Carrots", category: "Vegetable" }]
4. Categorizing by Computed Logic
You can group by any computed boolean or range condition:
const students = [
{ name: "Alex", score: 85 },
{ name: "Sarah", score: 55 },
{ name: "Maria", score: 92 },
];
const passFailGroups = Object.groupBy(students, (s) => (s.score >= 70 ? "Passed" : "Failed"));
console.log(passFailGroups);
// { Passed: [Alex, Maria], Failed: [Sarah] }
5. Common Mistakes
- Expecting Map Keys:
Object.groupBy()coerces all returned keys to Strings. If you need non-string object keys, useMap.groupBy().
6. Try It Yourself
Write it yourself. The tests below run against your code.
Group Inventory Items by Category
Examples
7. Next Steps
Use Object.groupBy() to categorize frontend table lists. Next, let's enter Phase 4 and master Asynchronous JavaScript!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.