Home > Back-end >  javascript Convert array of objects to single row of sum
javascript Convert array of objects to single row of sum

Time:07-08

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

CodePudding user response:

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.

  • Related