Skip to content
Advertisement

how to modify an array of objects with certain groups in to and array of object with group and related items?

I have the following array of object that I want to chance its structure , I am trying to use reduce to get a new object with element that have the same group..

const arr = [{id: 'c8c443', group: 'a', equipment: 'ball'},
              {id: 'c84445', group: 'a', equipment: 'ball'},
              {id: 'c8c655', group: 'b', equipment: 'basketball'},
              {id: 'c8c634', group: 'b', equipment: 'basketball'}]
         
 const newArr = arr.reduce(
    (obj: any, value: any, i) => [
      ...obj,
      {
        group: value.map((el: any) => el.group),
        items: value.map((el: any) => el.equipment),
      },
    ],
    []
  );
// Results  [{group: 'a', items: ['ball','ball']}, {group: 'b', items: ['basketball','basketball']}]

Advertisement

Answer

Here is an example:

const arr = [{id: 'c8c443', group: 'a', equipment: 'ball'},
             {id: 'c84445', group: 'a', equipment: 'ball'},
             {id: 'c8c655', group: 'b', equipment: 'basketball'},
             {id: 'c8c634', group: 'b', equipment: 'basketball'}]

const newArr = arr.reduce((acc, item) => {
  if (acc.some(key => key.group === item.group)) {
    acc = acc.map(i => i.group === item.group ? {...i, items: [...i.items, item.equipment]} : i)
  } else {
    acc.push({
      group: item.group,
      items: [item.equipment]
    })
  }

  return acc
}, [])

console.log(newArr)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement