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.
ES2024 introduced Object.groupBy(), a native JavaScript method to group array elements according to category keys returned by a testing callback function.
Previously, grouping array items required writing complex .reduce() accumulators. Object.groupBy() performs categorization natively in 1 clean line.
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" }]
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] }
Object.groupBy() coerces all returned keys to Strings. If you need non-string object keys, use Map.groupBy().Write it yourself. The tests below run against your code.
Use Object.groupBy() to categorize frontend table lists. Next, let's enter Phase 4 and master Asynchronous JavaScript!
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.
`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.
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.