ashwanikumarjha
Thu Dec 21 2023
The groupBy
method introduced in ES12 can be used to group elements based on the values returned by the specified callback function. This can be useful when we want to categorize items into distinct groups.
For example, consider a list of transactions and we want to group them by the account type:
const transactions = [
{ account: 'savings', amount: 12, date: '2023-01-01' },
{ account: 'checking', amount: 200, date: '2023-01-01' },
{ account: 'savings', amount: 500, date: '2023-02-01' },
{ account: 'checking', amount: 300, date: '2023-02-01' },
];
We can use groupBy
to group these transactions by their account type:
const groupedTransactions = Object.groupBy(transactions, ({ account }) => account);
The output will be:
{
savings: [
{ account: 'savings', amount: 12, date: '2023-01-01' },
{ account: 'savings', amount: 500, date: '2023-02-01' }
],
checking: [
{ account: 'checking', amount: 200, date: '2023-01-01' },
{ account: 'checking', amount: 300, date: '2023-02-01' }
]
}