Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda