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 an array of objects by one of its elements

I have an array of objects that looks like this

arr = [{
  group: "Forest",
  value: "81.8",
  year: 2015
}, {
  group: "Forest",
  value: "86.4",
  year: 2016
}, {
  group: "Forest",
  value: "67.3",
  year: 2017
}, {
  group: "Forest",
  value: "70.8",
  year: 2018
}, {
  group: "Forest",
  value: "67.6",
  year: 2019
}, {
  group: "Mountain",
  value: "78.6",
  year: 2015
}, {
  group: "Mountain",
  value: "83.1",
  year: 2016
}, {
  group: "Mountain",
  value: "65.6",
  year: 2017
}, {
  group: "Mountain",
  value: "68.1",
  year: 2018
}, {
  group: "Mountain",
  value: "63.7",
  year: 2019
}];

Is there a way to group this array by group? I want to create something like this or alike:

arr = [{
    group: "Forest",
    val2015: 81.8,
    val2016: 86.4,
    val2017: 67.3,
    val2018: 70.8,
    val2019: 67.6
},{
    group: "Mountain",
    val2015: 78.6,
    val2016: 83.1,
    val2017: 65.6,
    val2018: 68.1,
    val2019: 63.7
}];

Is it possible to do that with js, or maybe I can send arr to ajax and do this with php then return it?

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 :

You can create a Map to key the groups by the group strings, and associate to those keys plain objects, each with the group property.

Then iterate the data to populate those objects by year/value combinations.

Finally extract those objects from the Map:

const arr = [{group: "Forest",value: "81.8",year: 2015}, {group: "Forest",value: "86.4",year: 2016}, {group: "Forest",value: "67.3",year: 2017}, {group: "Forest",value: "70.8",year: 2018}, {group: "Forest",value: "67.6",year: 2019}, {group: "Mountain",value: "78.6",year: 2015}, {group: "Mountain",value: "83.1",year: 2016}, {group: "Mountain",value: "65.6",year: 2017}, {group: "Mountain",value: "68.1",year: 2018}, {group: "Mountain",value: "63.7",year: 2019}];

const groups = new Map(arr.map(({group}) => [group, { group }]));
for (const {group, value, year} of arr) {
    groups.get(group)["val" + year] = +value;
}
const result = [...groups.values()];

console.log(result);
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