I have the following data structure in its simplest form:
items: [
{ id: 1, account: 'acct_101' },
{ id: 2, account: 'acct_52' },
{ id: 3, account: 'acct_33' },
{ id: 4, account: 'acct_101' },
{ id: 5, account: 'acct_101' },
]
I would like to separate the items into groups based on their account data. The data is dynamic; I don’t know in advance what the account numbers may be.
I can loop through the data:
items.map((item) => (
console.log("item account: ", item.account)
))
Yet unsure how to match if an item.account
already exists and if so add to an existing data object, if not create a new object group.
The desired output could like like this:
item_groups: [
{
acct_101: [
{ id: 1, account: 'acct_101' },
{ id: 4, account: 'acct_101' },
{ id: 5, account: 'acct_101' },
],
acct_52: [
{ id: 2, account: 'acct_52' },
],
acct_33: [
{ id: 2, account: 'acct_33' },
],
}
]
3
Answers
Try like below:
More shorter form:
Using Array.prototype.reduce()
For your desired output I think you need to use reduce higher order function.
So your code will be :
Output :