xxxxxxxxxx
const list = [1, 2, 3, 4, 5];
console.log(list.reduce((number, nextNumber) => number + nextNumber));
// --> 15
xxxxxxxxxx
var array = [36, 25, 6, 15];
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // 36 + 25 + 6 + 15 = 82
xxxxxxxxxx
const arr = [1, 2, 3]
const result = arr.reduce((acc, curr) => acc + curr, 0)
// 1 + 2 + 3 = 6
console.log(result)
xxxxxxxxxx
const sum = array.reduce((accumulator, element) => {
return accumulator + element;
}, 0);
xxxxxxxxxx
// define a reusable function
const calculateSum = (arr) => {
return arr.reduce((total, current) => {
return total + current;
}, 0);
}
// try it
console.log(calculateSum([1, 2, 3, 4, 5]));
xxxxxxxxxx
/*
This method takes a callback that takes two parameters,
one that represents the element from the last iteration and the other is the current
element of the iteration
*/
let nums = [2,4,6,8,3,5]
let result = nums.reduce((prev,curr)=>prev+curr)
console.log(result); // 28
xxxxxxxxxx
[3, 2.1, 5, 8].reduce((total, number) => total + number, 0)
// loop 1: 0 + 3
// loop 2: 3 + 2.1
// loop 3: 5.1 + 5
// loop 4: 10.1 + 8
// returns 18.1
xxxxxxxxxx
You can return whatever you want from reduce method, reduce array method good for computational problems
const arr = [36, 25, 6, 15];
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // this will return Number
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, []); // this will return array
let {total} = array.reduce(function(accumulator, currentValue) {
let {currentVal} = currentValue
return accumulator + currentVal;
}, {
total: 0
}); // this will return object
And one additional rule is always always retrun the first param, which do arithmetic operations.
xxxxxxxxxx
let numbers = [1, 2, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
});