JavaScript Object.groupBy — Group an Array by Property
Turn a list of products into categories with Object.groupBy.
The live editor loads here with JavaScript enabled.
Run in Playground ↗The original source and explanation are available below.
Changes here stay separate from your main playground. Use Open in TryJS inside the editor to keep working with your changes.
Useful? Help keep TryJS free and independent.
Support TryJSWhat to expect
The products are grouped into books and games. Their totals are 30 and 35.
About this example
Grouping is useful when turning flat API data into sections, reports or summaries. Object.groupBy creates groups from a callback; a second pass can calculate a total for each group. This example uses local data and makes no API requests.
How It Works
Return the group key
Object.groupBy calls the callback for each product and puts it under the returned category. It requires a browser with Object.groupBy support.
Summarize each group
Object.entries exposes each category and its products. reduce calculates the total without changing the original list.
Read the original source
This is the starting code. Your edits stay in the live editor above.
JavaScript
const products = [
{ name: "Notebook", category: "books", price: 12 },
{ name: "Novel", category: "books", price: 18 },
{ name: "Puzzle", category: "games", price: 35 },
];
const groups = Object.groupBy(products, product => product.category);
console.log("Groups:", groups);
const totals = Object.fromEntries(
Object.entries(groups).map(([category, items]) => [
category,
items.reduce((total, product) => total + product.price, 0),
])
);
console.log("Totals:", totals);