Search code examples
javascriptarraysduplicatesjavascript-objects

Combine object values within an array using key value


I'm trying to group the follow array by id.

Ive tried using lodash, but my result is also duplicating id i.e "id":[6,6,6,6]

This is my existing array;

[
  {
    "nestedGroups": 64,
    "id": 6
  },
  {
    "nestedGroups": 27,
    "id": 6
  },
  {
    "nestedGroups": 24,
    "id": 6
  },
  {
    "nestedGroups": 69,
    "id": 6
  }
]

My expected outcome is to combine the nestedGroups into an array using the id as the key.

[
  {
    "nestedGroups": [64,27,24,69],
    "id": 6
  }
]

Solution

  • You can use reduce() and find()

    let arr = [ { "nestedGroups": 64, "id": 6 }, { "nestedGroups": 27, "id": 6 }, { "nestedGroups": 24, "id": 6 }, { "nestedGroups": 69, "id": 6 } ]
    
    const res = arr.reduce((ac,a) => {
      let temp = ac.find(x => x.id === a.id);
      if(!temp) ac.push({...a,nestedGroups:[a.nestedGroups]})
      else temp.nestedGroups.push(a.nestedGroups)
      return ac;
    },[])
    console.log(res)