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' },
],
}
]
>Solution :
Try like below:
const 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' },
]
const output = items.reduce((prev, curr) => {
if(prev[curr.account]) {
prev[curr.account].push(curr)
} else {
prev[curr.account] = [curr]
}
return prev
}, {})
console.log([output])
More shorter form:
const 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' },
]
const output = items.reduce((prev, curr) => {
prev[curr.account] = (prev[curr.account] ?? []).concat(curr)
return prev
}, {})
console.log([output])
Using Array.prototype.reduce()