1arr = [{x:1}, {x:3}]
2
3arr.reduce((accumulator, current) => accumulator + current.x, 0);
1var accounts = [
2 { name: 'James Brown', msgCount: 123 },
3 { name: 'Stevie Wonder', msgCount: 22 },
4 { name: 'Sly Stone', msgCount: 16 },
5 { name: 'Otis Redding', msgCount: 300 } // Otis has the most messages
6];
7
8// get sum of msgCount prop across all objects in array
9var msgTotal = accounts.reduce(function(prev, cur) {
10 return prev + cur.msgCount;
11}, 0);
12
13console.log('Total Messages:', msgTotal); // Total Messages: 461
1const getSumByKey = (arr, key) => {
2 return arr.reduce((accumulator, current) => accumulator + Number(current[key]), 0)
3}
4
5arr = [{x:1}, {x:3}]
6getSumByKey(arr, 'x') // returns 4
7
1 run.addEventListener("click", function () {
2 let sum = people.reduce(function (a, b) { // function(previousValue, currentValue)
3 return {
4 age: a.age + b.age, //select age in object array
5 };
6 });
7 console.log(sum); //output sum of ages
8 });
1const fruitTally = fruit.reduce((currentTally, currentFruit) => {
2 currentTally[currentFruit] = (currentTally[currentFruit] || 0) + 1
3 return currentTally
4} , {})
5// returns {"apple":3,"banana":3,"cherry":2,"mango":2,"apricot":1,"guava":2}