xxxxxxxxxx
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 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
let array = [36, 25, 6, 15];
array.reduce((acc, curr) => acc + curr, 0)
// 36 + 25 + 6 + 15 = 82
c7208648b19086ffaef0da34bbb912f6
xxxxxxxxxx
const arr = [3, 5, 4, 11, 7, 22];
arr.reduce((previousValue, currentValue) => {
return previousValue + currentValue; // <--- 3 + 5 + 4 + 11 + 7 + 22 = 52
}, 0)
xxxxxxxxxx
var depthArray = [1, 2, [3, 4], 5, 6, [7, 8, 9]];
depthArray.reduce(function(flatOutput, depthItem) {
return flatOutput.concat(depthItem);
}, []);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9];
// --------------
const prices = [100, 200, 300, 400, 500];
const total = prices.reduce((total, cur) => {return total + cur} )
// init value = 0 => total = 1500;
// --------------
const prices = [100, 200, 300, 400, 500];
const total = prices.reduce(function (total, cur) => {
return total + cur
}, 1 )
// init value = 1 => so when plus all numnber will be result => 1501;
// --------------
const prices = [100, 200, 300, 400, 500];
const total = prices.reduce((total, cur) => total + cur )
// 1500;
Reduce in js
xxxxxxxxxx
let arr=[5,6,2];
let sum=arr.reduce((accumulator,current,index,arr)=>{
return accumulator+=current;
});
console.log(sum);//5+6+13
accumulator acumulate(hold) the sum output
reduce methood creat a new array and does not change actual array
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
const list = [1, 2, 3, 4, 5];
console.log(list.reduce((number, nextNumber) => number + nextNumber));
// --> 15