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

127
Views
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 answers
Answer question

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 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!