1

I have an Array of Objects like this

const obj = [
  {
    id: 1,
    name: "Abc"
  },
  {
    id: 2,
    name: "BED"
  },
  {
    id: 1,
    name: "FGH"
  },
  {
    id: 3,
    name: "RFS"
  },
  {
    id: 1,
    name: "Abc"
  },
  {
    id: 2,
    name: "BGH"
  }
]

I want to club the objects who have same id and same name so that my Final output looks like this-

const result = [
  [
    {
      id: 1,
      name: "Abc"
    },
    {
      id: 1,
      name: "Abc"
    }
  ],
  [
    {
      id: 1,
      name: "TSD"
    }
  ],
  [
    {
      id: 2,
      name: "BED"
    }       
  ],
  [
      {
      id: 2,
      name: "BGH"
    }
  ],
  [
    {
      id: 3,
      name: "RFS"
    }
  ]
]

Note - I have about 300-400 objects in the array and I have used nested For loops to solve this problem. Therefore I am looking for a better and fast solution

Aakash_Sardana
  • 260
  • 1
  • 8

1 Answers1

2

You can use reduce() and use object accumulator. And at the end use Object.values to get an array.

const obj = [ { id: 1, name: "Abc" }, { id: 2, name: "BED" }, { id: 1, name: "FGH" }, { id: 3, name: "RFS" }, { id: 1, name: "TSD" }, { id: 2, name: "BGH" } ]

let res = Object.values(obj.reduce((ac,a) => {
  if(!ac[a.id]) ac[a.id] = [];
  ac[a.id].push(a);
  return ac;
},{}))

console.log(res)

Using for...of

const obj = [ { id: 1, name: "Abc" }, { id: 2, name: "BED" }, { id: 1, name: "FGH" }, { id: 3, name: "RFS" }, { id: 1, name: "TSD" }, { id: 2, name: "BGH" } ]

let res = {};

for(let item of obj){
  if(!res[item.id]) res[item.id] = [];
  res[item.id].push(item);
}

console.log(Object.values(res))
Community
  • 1
  • 1
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73