javascript - reduce without return but assign to a variable failed -


using reduce possible sum value without returning assign outer variable? got error of nan using below code.

const raw = [{   "age_data": [{     "male_count": 13,     "female_count": 13   }, {     "male_count": 452,     "female_count": 470   }] }, {   "age_data": [{     "male_count": 1,     "female_count": 2   }, {     "male_count": 58,     "female_count": 32   }] }]  let total_male_count, total_female_count = 0 raw.foreach(obj => {   obj.age_data.reduce((accum, obj2) => {     total_male_count = accum + obj2.male_count     total_female_count = accum + obj2.female_count   }, 0) })  console.log(total_male_count) console.log(total_female_count) 

https://jsfiddle.net/l6ttsl8t/

i'm not sure what's wrong accum, obj2.male_count did return value.

you don't use reduce if you're not using return value. you're doing, use foreach.

your total_male_count not initialized, starts out containing undefined (you've initialized total_female_count). further, want add total_... variables, not use accumulator.

so, initialize it, add existing variables, , use correct "looping" function, , you'll correct value.

let total_male_count = 0, total_female_count = 0 // -----------------^^^^ raw.foreach(obj => {   obj.age_data.foreach(obj2 => { // ------------^^^^^^^^^^^^     total_male_count += obj2.male_count // ------------------^^     total_female_count += obj2.female_count // --------------------^^   }, 0) }) 

live example:

const raw = [{    "age_data": [{      "male_count": 13,      "female_count": 13    }, {      "male_count": 452,      "female_count": 470    }]  }, {    "age_data": [{      "male_count": 1,      "female_count": 2    }, {      "male_count": 58,      "female_count": 32    }]  }]    let total_male_count = 0, total_female_count = 0  raw.foreach(obj => {    obj.age_data.foreach(obj2 => {      total_male_count += obj2.male_count      total_female_count += obj2.female_count    }, 0)  })    console.log(total_male_count)  console.log(total_female_count)


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -