Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading