Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through map and push to a new object group if items have matching values

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading