1var array = [36, 25, 6, 15];
2
3array.reduce(function(accumulator, currentValue) {
4 return accumulator + currentValue;
5}, 0); // 36 + 25 + 6 + 15 = 82
1const numbers = [15.5, 2.3, 1.1, 4.7];
2document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
3
4function getSum(total, num) {
5 return total + Math.round(num);
6}
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)
1function reduce(array, func, seed) {
2 let previousResult;
3 if (seed === undefined) {
4 previousResult = array[0];
5 for (let i = 1; i < array.length; i++) {
6 previousResult = func(previousResult, array[i], i, array);
7 }
8 console.log(previousResult);
9 } else {
10 previousResult = seed;
11 each(array, function(e, i, a) {
12 previousResult = func(previousResult, e, i, array);
13 });
14 }
15 return previousResult;
16};
1/* this is our initial value i.e. the starting point*/
2const initialValue = 0;
3
4/* numbers array */
5const numbers = [5, 10, 15];
6
7/* reducer method that takes in the accumulator and next item */
8const reducer = (accumulator, item) => {
9 return accumulator + item;
10};
11
12/* we give the reduce method our reducer function
13 and our initial value */
14const total = numbers.reduce(reducer, initialValue)
15
1//note idx and sourceArray are optional
2const sum = array.reduce((accumulator, element[, idx[, sourceArray]]) => {
3 //arbitrary example of why idx might be needed
4 return accumulator + idx * 2 + element
5}, 0);