ES6+ Modern JavaScript
Array.groupBy & Object.groupBy
Master grouping collections in JavaScript. Learn the standard Object.groupBy and Map.groupBy APIs to group arrays of data dynamically.
1. Introduction
Grouping lists of items based on a property is a common data processing task. ES2024 introduced two static methods, Object.groupBy() and Map.groupBy(), to group array elements dynamically without needing third-party libraries.
2. Why It Matters
Historically, grouping arrays required writing custom reduce() loops or loading utility libraries like Lodash. The new static grouping methods simplify these operations, providing a clean, standard way to group collections.
3. Real-World Analogy
Think of a Post Office Sorting Table:
- Legacy reduce() method: A worker takes each letter, walks to the sorting rack, checks if a cubby exists for that city, builds the cubby if missing, places the letter inside, and repeats for all letters. This requires writing separate steps for each action.
- Object.groupBy (Automatic Sorting Machine): A machine that reads the city label on each letter and places it directly into the correct box automatically. It separates the sorting rules from the sorting process.
4. Object.groupBy
Object.groupBy() groups elements of an iterable into a plain JavaScript object. The keys of the returned object are the values returned by the callback function, and the values are arrays containing the grouped elements:
5. Map.groupBy
Map.groupBy() groups elements into a standard Map object. This is useful when you want to use objects or other non-string data types as the grouping keys:
6. Practical Example
This script demonstrates grouping numerical scores into grade categories using Object.groupBy:
7. Common Mistakes
- Using Object.groupBy when you need object references as keys: Plain objects only support strings or symbols as keys. If you return an object from the callback function in
Object.groupBy(), the object is converted to the string"[object Object]", which can cause keys to overwrite each other. UseMap.groupBy()instead when grouping by object references.
8. Quick Quiz
Q1: Which static method should you use to group elements when you want to use object references as the grouping keys?
A) Object.groupBy()
B) Map.groupBy()
Answer: B — Map.groupBy() returns a standard Map object, which supports keys of any data type, including object references.
9. Scenario-Based Challenge
The Project Milestone Classifier:
A project management board lists task objects containing dates: { title: "A", dueDate: "2026-07-20" }. Group these tasks into "Overdue", "Due Today", and "Future" categories based on the current system date. Write the grouping callback logic.
10. Debugging Exercise
Explain why all items group under the same key "[object Object]" in this script:
const categories = { active: { id: 1 }, inactive: { id: 2 } };const users = [ { name: 'Alice', status: categories.active }, { name: 'Bob', status: categories.inactive } ];
// Objective: group users by category status object reference const result = Object.groupBy(users, (u) => u.status); console.log(result); // logs { "[object Object]": [...] }! Why?
View Solution
Diagnosis: The Object.groupBy() method converts keys to strings. Since the callback returns a status object reference, the browser converts it to the string "[object Object]", causing all users to group under the same key.
Fix: Switch to Map.groupBy() to preserve the object references as keys in the returned Map:
const result = Map.groupBy(users, (u) => u.status);
console.log(result.get(categories.active)); // Returns Alice's user object successfully!
11. Interview Questions
🟢 Q1: Compare Object.groupBy() and Map.groupBy() and list their key differences.
Answer:
• Object.groupBy(): Groups elements into a plain JavaScript object. Keys are coerced to strings. This is best for simple groupings using string or symbol categories.
• Map.groupBy(): Groups elements into a standard Map object. Keys are not coerced, allowing you to use keys of any data type, including object references. This is best when you need to group by object references or map records to metadata instances.
12. Production Considerations
- • Browser Support:
Object.groupByandMap.groupByare ES2024 features. Ensure your target environment supports them, or include a polyfill (like core-js) if building production bundles for older browsers.