javascript / intermediate
Snippet
Efficient Data Grouping with Array.reduce
Array.reduce is a powerful tool for transforming an array into a single object or value. In this intermediate pattern, we use an object as an accumulator to group and sum data based on a specific property.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const transactions = [{ id: 1, type: 'income', amount: 100 },{ id: 2, type: 'expense', amount: 50 },{ id: 3, type: 'income', amount: 200 }];const summary = transactions.reduce((acc, current) => {acc[current.type] = (acc[current.type] || 0) + current.amount;return acc;}, {});console.log(summary); // { income: 300, expense: 50 }
nextjs
Breakdown
1
acc[current.type] = (acc[current.type] || 0) + current.amount;
Initializes the property to 0 if it doesn't exist, then adds the current amount.
2
}, {});
Specifies an empty object as the initial value for the accumulator.