Add one property and Multiply another property using a Javascript Reduce

3178 views javascript
2

var modifiers = [
    { plus : 2, times : 2},
    { plus : 0, times : 1.2},
    { plus : 10, times : 1},
    { plus : 1, times : 1.7},   

];

If I wanted to add all the pluses and multiply all the timeses together I could do it in a loop like this

function calc(modifiers) {
    var plus = 0;
    var times = 1;
    for (var mod of modifiers) 
    {
        plus += mod.plus
        times *= mod.times
    }
    return plus * times
}

Is it possible to do the same thing using a single reduce, or would I have to do 2 reduces

answered question

1 Answer

10

Sure, just use the object as the accumulator and return a summary object with both values:

var modifiers = [
    { plus : 2, times : 2},
    { plus : 0, times : 1.2},
    { plus : 10, times : 1},
    { plus : 1, times : 1.7},   

];

let summary = modifiers.reduce((obj, current) => {
    obj.plus += current.plus
    obj.times *= current.times
    return obj
})
console.log(summary)

posted this

Have an answer?

JD

Please login first before posting an answer.