Home > database >  how to Sum the max from two keys similarly, object javascript [closed]
how to Sum the max from two keys similarly, object javascript [closed]

Time:09-28

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

CodePudding user response:

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);

CodePudding user response:

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)

  • Related