javascript / intermediate
Snippet
Grouping Categorized Items in React State with Object.groupBy
The native `Object.groupBy()` static method reorganizes iterable collections into plain objects keyed by callback return values. In React components, this eliminates manual reduce boilerplates when transforming flat arrays into grouped rendering structures.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function InventoryDashboard({ rawInventory = [] }) {const [inventoryList] = React.useState(rawInventory);// Group items by category string using the standard Object.groupBy APIconst groupedByCategory = Object.groupBy(inventoryList,(item) => item.department ?? 'Unassigned');return (<section><h2>Department Inventory</h2>{Object.entries(groupedByCategory).map(([department, items]) => (<div key={department}><h3>{department} ({items.length})</h3><ul>{items.map((item) => (<li key={item.id}>{item.name} - ${item.price}</li>))}</ul></div>))}</section>);}
react
Breakdown
1
const groupedByCategory = Object.groupBy(
Calls the built-in ES2024 grouping utility directly on the state array.
2
(item) => item.department ?? 'Unassigned'
Extracts the group key with nullish coalescing to safely group items missing a department.
3
{Object.entries(groupedByCategory).map(([department, items]) => (
Converts grouped dictionary entries into an array of key-value pairs for iterative JSX rendering.