简体   繁体   中英

Add one property and Multiply another property using a Javascript Reduce

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

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((a, {plus, times}) => ({plus: a.plus + plus, times: a.times * times})) console.log(summary) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM