-1

I have the following array

array1 = [{
    category: "Age"
    id: "11"
  },
  {
    category: "Gender"
    id: "M"
  },
  {
    category: "Age"
    id: "23"
  },
  {
    category: "Gender"
    id: "F"
  },
  {
    category: "Education"
    id: "Graduate"
  },
  {
    category: "Age"
    id: "55"
  }
]

I want this to group by category, something like this

groupedArray = [{
  category: "Age",
  groupedCat: [{
      category: "Age"
      id: "11"
    },
    {
      category: "Age"
      id: "23"
    },
    {
      category: "Age"
      id: "55"
    }
  ],
  category: "Gender",
  groupedCat: [{
      category: "Gender"
      id: "M"
    },
    {
      category: "Gender"
      id: "F"
    }
  ],
  category: "Education",
  groupedCat: [{
    category: "Education"
    id: "Graduate"
  }]
}]
Prasun
  • 4,943
  • 2
  • 21
  • 23
Jimi
  • 3
  • 2

1 Answers1

0

you can do it like this:

var array1 = [{
  category: "Age",
  id: "11"
}, {
  category: "Gender",
  id: "M"
}, {
  category: "Age",
  id: "23"
}, {
  category: "Gender",
  id: "F"
}, {
  category: "Education",
  id: "Graduate"
}, {
  category: "Age",
  id: "55"
}];

let res = {};
for (var o of array1) {
  if (res[o.category] === undefined) {
    res[o.category] = [];
  }
  res[o.category].push(o);
}
console.log(res);

Note that this is not exactly as you wanted from your question above, I instead used the category as the key for the object. I assume this is what you're looking for. If not leave a comment and I could update.

Hope this helps,

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33