xxxxxxxxxx
arr.reduce(callback( accumulator, currentValue[, index[, array]] ) {
// return result from executing something for accumulator or currentValue
}[, initialValue]);
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
// syntax: array.reduce(function, accumulator-initial-value)
let array = [3, 7, 2, 9, 5]
const result = array.reduce((accumulator, currentValue, currentIndex, arr) => {
// code
}, initialValue)
// accumulator = will store return value of the function
// currentValue = iterate through each array element
// currentIndex = index of currentValue
// arr = original array
// initialValue = set accumulator initial value
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
Sum array elements:
let myArr = [1,2,3,-1,-34,0]
return myArr.reduce((a,b) => a + b,0)
xxxxxxxxxx
// Arrow function
reduce((previousValue, currentValue) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)
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
const values = [4, 3, 2, 1];
console.log("Before reduce");
const sum = values.reduce((accumulator, current) => {
const result = accumulator + current;
console.log(
`accumulator: ${accumulator}, current: ${current}, result: ${result}`
);
//accumulator will be used to store the result and will be used in the next iteration
return result;
});
console.log("After reduce");
// Before reduce
// accumulator: 4, current: 3, result: 7
// accumulator: 7, current: 2, result: 9
// accumulator: 9, current: 1, result: 10
// After reduce
console.log(sum); // => 10
reduce
xxxxxxxxxx
var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6