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

Group by a set of JavaScript Objects

I’ve got this set of data :

  { CIRPIC: 'AUA', ALLPIC: 2 },
  { CIRPIC: 'AUA', ALLPIC: 3 },
  { CIRPIC: 'AUA', ALLPIC: 1 },
  { CIRPIC: 'AUA', ALLPIC: 4 },
  { CIRPIC: 'AUF', ALLPIC: 12 },
  { CIRPIC: 'AU3', ALLPIC: 2 },
  { CIRPIC: 'AU3', ALLPIC: 7 },

And I would like it to be like this :

{CIRPIC: 'AUA', ALLPIC: [2,3,1,4]},
{CIRPIC: 'AUF', ALLPIC: [12]},
{CIRPIC: 'AU3', ALLPIC: [2,7]},

Thanks for your help

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

>Solution :

var groupBy = allees.reduce(function (obj, item) {
    obj[item.CIRPIC] = obj[item.CIRPIC] || [];
    obj[item.CIRPIC].push(item.ALLPIC);
    return obj;
}, {});

const newArray = Object.keys(groupBy).map(function (key) {
    return {CIRPIC: key, ALLPIC: groupBy[key]};
});
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