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

129
Vistas
javascript Convert array of objects to single row of sum

I want to sum all rows to a single row in javascript array

var input=[
    {id: 'id1', type: "A", active: 3},
    {id: 'id2', type: "A", active: 5},
    {id: 'id3', type: "B", active: 3},
    {id: 'id4', type: "B", active: 4},
    {id: 'id5', type: "C", active: 8},
    {id: 'id6', type: "C", active: 5},
    {id: 'id7', type: "C", active: 6},
    {id: 'id8', type: "C", active: 7},
];

expected output

[
    {id: NaN, type: NaN, active: 41}
]

var input=[
    {id: 'id1', type: "A", active: 3},
    {id: 'id2', type: "A", active: 5},
    {id: 'id3', type: "B", active: 3},
    {id: 'id4', type: "B", active: 4},
    {id: 'id5', type: "C", active: 8},
    {id: 'id6', type: "C", active: 5},
    {id: 'id7', type: "C", active: 6},
    {id: 'id8', type: "C", active: 7},
];
const t1 = performance.now();
var output=[{}];Object.keys(input[0]).forEach(function(item){
    var s=0;
    input.forEach(function(itema){
        s+=parseInt(itema[item]);
    });
    if(!isNaN(s))
        output[0][item]=s;
    else
        output[0][item]='';
})
const t2 = performance.now();
console.log('output:', output, `in ${t2 - t1}ms`);

Is there another easier way? Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use reduce to integer sum each entry in each object.

const input = [{"id":"id1","type":"A","active":3},{"id":"id2","type":"A","active":5},{"id":"id3","type":"B","active":3},{"id":"id4","type":"B","active":4},{"id":"id5","type":"C","active":8},{"id":"id6","type":"C","active":5},{"id":"id7","type":"C","active":6},{"id":"id8","type":"C","active":7}];

const t1 = performance.now();
const output = input.reduce((acc, obj) =>
  Object.fromEntries(
    Object.entries(acc).map(([key, val]) => [
      key,
      parseInt(val, 10) + parseInt(obj[key], 10),
    ])
  )
);
const t2 = performance.now();

console.log(output, `in ${t2 - t1}ms`);

This should work with any flat object structure, provided all objects in the array are the same shape.

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