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
1const sum = array.reduce((accumulator, element) => {
2 return accumulator + element;
3}, 0);
4// An example that will loop through an array adding
5// each element to an accumulator and returning it
6// The 0 at the end initializes accumulator to start at 0
7// If array is [2, 4, 6], the returned value in sum
8// will be 12 (0 + 2 + 4 + 6)
9
10const product = array.reduce((accumulator, element) => {
11 return accumulator * element;
12}, 1);
13// Multiply all elements in array and return the total
14// Initialize accumulator to start at 1
15// If array is [2, 4, 6], the returned value in product
16// will be 48 (1 * 2 * 4 * 6)
1const array1 = [1, 2, 3, 4];
2const reducer = (accumulator, currentValue) => accumulator + currentValue;
3
4// 1 + 2 + 3 + 4
5console.log(array1.reduce(reducer));
6// expected output: 10
7
8// 5 + 1 + 2 + 3 + 4
9console.log(array1.reduce(reducer, 5));
10// expected output: 15
1The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
2
3The reducer function takes four arguments:
4Accumulator (acc)
5Current Value (cur)
6Current Index (idx)
7Source Array (src)
8
9//syntax
10arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
11//example flatten an array
12
13let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
14 ( accumulator, currentValue ) => accumulator.concat(currentValue),
15 []
16)
1function reduce(array, combine, start) {
2 let current = start;
3 for (let element of array) {
4 current = combine(current, element);
5 }
6 return current;
7}
8
9console.log(reduce([1, 2, 3, 4], (a, b) => a + b, 0));
10// → 10