Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!