Search code examples
javascriptnode.jsarrayssummax

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


Solution

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