xxxxxxxxxx
Sum array elements:
let myArr = [1,2,3,-1,-34,0]
return myArr.reduce((a,b) => a + b,0)
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
let array = [36, 25, 6, 15];
array.reduce((acc, curr) => acc + curr, 0)
// 36 + 25 + 6 + 15 = 82
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
// 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