javascript reduce
var array = [36, 25, 6, 15];
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // 36 + 25 + 6 + 15 = 82
javascript reduce
var array = [36, 25, 6, 15];
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // 36 + 25 + 6 + 15 = 82
syntax of reduce in js
[1,2,3,4,5].reduce((acc, current)=>acc+current, 0)
reduce method
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
The reducer function takes four arguments:
Accumulator (acc)
Current Value (cur)
Current Index (idx)
Source Array (src)
//syntax
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
//example flatten an array
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( accumulator, currentValue ) => accumulator.concat(currentValue),
[]
)
javascript reduce
let arr = [1,2,3]
/*
reduce takes in a callback function, which takes in an accumulator
and a currentValue.
accumulator = return value of the previous iteration
currentValue = current value in the array
*/
// So for example, this would return the total sum:
const totalSum = arr.reduce(function(accumulator, currentVal) {
return accumulator + currentVal
}, 0);
> totalSum == 0 + 1 + 2 + 3 == 6
/*
The '0' after the callback is the starting value of whatever is being
accumulated, if omitted it will default to whatever the first value in
the array is, i.e:
> totalSum == 1 + 2 + 3 == 6
if the starting value was set to -1 for ex, the totalSum would be:
> totalSum == -1 + 1 + 2 + 3 == 5
*/
// arr.reduceRight does the same thing, just from right to left
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us