1let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
2 function(accumulator, currentValue) {
3 return accumulator.concat(currentValue)
4 },
5 []
6)
7// flattened is [0, 1, 2, 3, 4, 5]
8
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
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
1var array = [36, 25, 6, 15];
2
3array.reduce(function(accumulator, currentValue) {
4 return accumulator + currentValue;
5}, 0); // 36 + 25 + 6 + 15 = 82
1// Reduce() method executes a callback function that is passed in
2// on each element of the array, resulting in single output value.
3const array1 = [1, 2, 3, 4];
4const callback = (accumulator, currentValue) => accumulator + currentValue;
5
6// 1 + 2 + 3 + 4
7console.log(array1.reduce(callback));
8// expected output: 10
9
10// 5 + 1 + 2 + 3 + 4
11console.log(array1.reduce(callback, 5));
12// expected output: 15 because the initial value is 5.
13
14// This is how Reduce works.
15// This is a myReduce method which takes a callback and an optional argument
16// of a default accumulator. If myReduce only receives one argument, then
17// myReduce will use the first element as the accumulator.
18
19Array.prototype.myReduce = function(callback, acc) {
20 if (!acc) {
21 acc = this.shift();
22 }
23 this.forEach(function(element) {
24 acc = callback(acc, element)
25 })
26 return acc;
27}