Home > OS >  Group an array of objects by one of its elements
Group an array of objects by one of its elements

Time:05-06

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?

CodePudding user response:

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);

  • Related