1var objs = [
2 {name: "Peter", age: 35},
3 {name: "John", age: 27},
4 {name: "Jake", age: 28}
5];
6
7objs.reduce(function(accumulator, currentValue) {
8 return accumulator + currentValue.age;
9}, 0); // 35 + 27 + 28 = 90
1var array = [36, 25, 6, 15];
2
3array.reduce(function(accumulator, currentValue) {
4 return accumulator + currentValue;
5}, 0); // 36 + 25 + 6 + 15 = 82
1function getArraySum(a){
2 var total=0;
3 for(var i in a) {
4 total += a[i];
5 }
6 return total;
7}
8
9var payChecks = [123,155,134, 205, 105];
10var weeklyPay= getArraySum(payChecks); //sums up to 722
1// Array.prototype.reduce()
2
3const array1 = [1, 2, 3, 4];
4const reducer = (accumulator, currentValue) => accumulator + currentValue;
5
6// 1 + 2 + 3 + 4
7console.log(array1.reduce(reducer));
8// expected output: 10
9
10// 5 + 1 + 2 + 3 + 4
11console.log(array1.reduce(reducer, 5));
12// expected output: 15
1var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
2=> 6
3
1const arr = [5, 7, 1, 8, 4];const sum = arr.reduce(function(accumulator, currentValue) { return accumulator + currentValue;});// prints 25console.log(sum);