Organize array elements into dictionary categories using the modern ES2024 Object.groupBy() static method.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
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().Use Object.groupBy() to categorize frontend table lists. Next, let's enter Phase 4 and master Asynchronous JavaScript!