Answers for "reduce method js return value"

2

javascript reduce

/* reduce method: combine an array's values together, left to right */

let myArray = [1, 2, 3];

let a = myArray.reduce((initial, current) => initial + current, 0);
// [0 + 1 + 2 + 3] → 6

let b = myArray.reduce((initial, current) => initial + (current*10), 7);
// [7 + (1*10) + (2*10) + (3*10)] → 67

// Combine right to left with .reduceRight
let c = myArray.reduceRight((initial, current) => initial / current, 30);
// [30 / 3 / 2 / 1] → 5

/* Syntax: array.reduce((accumulator, currentValue) =>
combineFunction, accumulatorStartValue); */
Posted by: Guest on March-05-2022
0

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
Posted by: Guest on January-25-2022

Code answers related to "Javascript"

Browse Popular Code Answers by Language