Sub topic 3
Your First Object.groupBy Call
This chapter assumes you know JavaScript arrays and methods like map and reduce, arrow functions with destructuring, and plain object property access. You will make a basic Object.groupBy call and learn what it returns.
The Signature
Object.groupBy is a static method. You call it on Object itself, not on an array:
Object.groupBy(items, callbackFn)itemsis the collection to group. In this chapter it is always an array.callbackFnruns once for each element and returns that element's group key.- The return value is a new object. Each property name is a key the callback returned, and each property value is an array of the elements that produced that key.
The original array is not modified.
A Worked Example
Here is a small inventory list, grouped by each item's type:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
console.log(Object.keys(byType)); // ["vegetables", "fruit", "meat"]
console.log(byType.fruit.map((item) => item.name)); // ["bananas", "cherries"]The callback ({ type }) => type destructures each element and returns its type string. That string becomes the key. Object.groupBy handles the bookkeeping: it creates the array for a new key and appends to the existing array for a key it has already seen.
The result looks like this:
| Key | Group contents |
|---|---|
| `vegetables` | asparagus |
| `fruit` | bananas, cherries |
| `meat` | goat |
What Happens Step by Step
Two details follow from this process:
- Within each group, elements keep the order they had in the input.
bananascomes beforecherriesbecause it came first ininventory. - A group exists only if at least one element produced its key. There are no empty arrays. A key that never appeared reads as
undefined.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
console.log(byType.dairy); // undefined
console.log(byType.dairy?.length ?? 0); // 0When you read a group that might be missing, guard the read with optional chaining or a default.
Common Mistakes
- Calling it on the array.
inventory.groupBy(...)throws aTypeErrorbecause arrays have nogroupBymethod. UseObject.groupBy(inventory, ...). - Forgetting to return a key. A block-bodied arrow such as
(item) => { item.type }returnsundefined, so every element ends up under the key"undefined". Either addreturnor use a concise body. - Expecting copies. Each group array is new, but the elements inside it are the same objects as in the source array.
Exercise
Given const words = ["apple", "avocado", "banana", "blueberry", "cherry"];, write an Object.groupBy call that groups the words by their first letter. Then give the value of result.b and of result.z.
Show answer
const result = Object.groupBy(words, (word) => word[0]); Then result.b is ["banana", "blueberry"], with input order preserved, and result.z is undefined because no word starts with "z", so that group was never created.
Exercise
A teammate writes Object.groupBy(inventory, (item) => { item.type; }) and finds that every item lands in one group. What is that group's key, and how do you fix the code?
Show answer
The callback has a block body with no return, so it returns undefined for every element. Keys are converted to strings, so all items are grouped under "undefined". Fix it with (item) => item.type or (item) => { return item.type; }.