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

162
Views
how to Sum the max from two keys similarly, object javascript

I need the sum total of the object, where, but the maximum of each similar pair javascript

var score = {
    "work_1": 5,
    "work_1|pm": 10,
    "work_2": 8,
    "work_2|pm": 7
    "work_3": 10
};

the work_3 doesn't have a pair similar I wish this result

total = 28

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

0

Group the maximums by key-prefix in a new object, and then sum the values of that object. In both phases you can use reduce:

var score = {
    "work_1": 5,
    "work_1|pm": 10,
    "work_2": 8,
    "work_2|pm": 7,
    "work_3": 10
};

var result = Object.values(
    Object.entries(score).reduce((acc, [k, v]) => {
        k = k.split("|")[0];
        acc[k] = Math.max(v, acc[k] ?? v);
        return acc;
    }, {})
).reduce((a, b) => a + b, 0);

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You can get the property values of the object with Object.values, sort the resulting array, then sum the first 2 items:

var score = {
    "work_1": 5,
    "work_1|pm": 10,
    "work_2": 8,
    "work_2|pm": 7,
    "work_3": 10
};

const max2 = Object.values(score).sort().splice(0, 2)

const result = max2[0] + max2[1];
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!