简体   繁体   中英

How do I use reduce to calculate the total of a value in an object

 const people = [ { name: 'Matt', friend: true, awesomeLevel: 10 }, { name: 'Matias', friend: true, awesomeLevel: 10 }, { name: 'Catie', friend: false, awesomeLevel: 3 }, { name: 'Samantha', friend: false, awesomeLevel: 4 }, { name: 'Jonathan', friend: true, awesomeLevel: 8 }, { name: 'Josh', friend: true, awesomeLevel: 7 } ] let totallyAwesome = people.reduce((acc, ele) => acc + ele.awesomeLevel) console.log(totallyAwesome)

So I'm trying to use reduce to get the whole total added up of awesomeLevel

You need to add a initialValue for the accumulator. Otherwise the first element is taken as start value for Array#reduce .

 const people = [ { name: 'Matt', friend: true, awesomeLevel: 10 }, { name: 'Matias', friend: true, awesomeLevel: 10 }, { name: 'Catie', friend: false, awesomeLevel: 3 }, { name: 'Samantha', friend: false, awesomeLevel: 4 }, { name: 'Jonathan', friend: true, awesomeLevel: 8 }, { name: 'Josh', friend: true, awesomeLevel: 7 } ]; let totallyAwesome = people.reduce((acc, ele) => acc + ele.awesomeLevel, 0); // ^ console.log(totallyAwesome);

You only forget the starting-value 0 in your reduce at the end as second parameter (just after the callback).

 const people = [ { name: 'Matt', friend: true, awesomeLevel: 10 }, { name: 'Matias', friend: true, awesomeLevel: 10 }, { name: 'Catie', friend: false, awesomeLevel: 3 }, { name: 'Samantha', friend: false, awesomeLevel: 4 }, { name: 'Jonathan', friend: true, awesomeLevel: 8 }, { name: 'Josh', friend: true, awesomeLevel: 7 } ] let totallyAwesome = people.reduce((acc, {awesomeLevel}) => acc + awesomeLevel, 0); console.log(totallyAwesome)

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