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

78
Views
Selection Sum - Javascript

If I have an array of object like this one:

obj = [{id:1,value:2},{id:1,value:3},{id:2,value:8}]

How can I sum the values with the same id and return another array with the totals of each index?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use reduce to achieve that

const obj = [{
  id: 1,
  value: 2
}, {
  id: 1,
  value: 3
}, {
  id: 2,
  value: 8
}, {
  id: 3,
  value: 4
}, {
  id: 2,
  value: 1
}]

const result = Object.values(
  obj.reduce((a, { id, value }) => (((a[id] ??= { id, value: 0 }).value += value), a), {})
);

console.log(result)

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!