// 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
/*
This method takes a callback that takes two parameters,
one that represents the element from the last iteration and the other is the current
element of the iteration
*/
let nums = [2,4,6,8,3,5]
let result = nums.reduce((prev,curr)=>prev+curr)
console.log(result); // 28
arr.reduce(callback( accumulator, currentValue[, index[, array]] ) {
// return result from executing something for accumulator or currentValue
}[, initialValue]);
function reduce(array, combine, start) {
let current = start;
for (let element of array) {
current = combine(current, element);
}
return current;
}
console.log(reduce([1, 2, 3, 4], (a, b) => a + b, 0));
// → 10
You can return whatever you want from reduce method, reduce array method good for computational problems
const arr = [36, 25, 6, 15];
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // this will return Number
array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, []); // this will return array
let {total} = array.reduce(function(accumulator, currentValue) {
let {currentVal} = currentValue
return accumulator + currentVal;
}, {
total: 0
}); // this will return object
And one additional rule is always always retrun the first param, which do arithmetic operations.
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),
[]
)
const numbers = [260, 25, 35];
console.log(numbers.reduce(myFunc))
function myFunc(total, num) {
return total - num;
}
/*console.log will show 200 since the first element minus 35 and minus 25 is 260-25-35=200*/
/*while the name is "reduce", you do NOT have to subtract. Reduce() is more about "take the first element as total, and do something(whatever the function says) to it for each of the remaining elements; the remaining elements will be identified as the second parameter num for the function myFunc, you do whatever once for all remaining elements*/
//note idx and sourceArray are optional
const sum = array.reduce((accumulator, element[, idx[, sourceArray]]) => {
//arbitrary example of why idx might be needed
return accumulator + idx * 2 + element
}, 0);
// use of reduce on an array, returns an array into a single value
// define the array
let numbers = [25, 25, 20]
// using the .reduce() to ADD all the numbers into a single value
// we are storing the reduce method into a single variable called sum
let sum = numbers.reduce(function(total, current) {
return total + current // adds the current value (10) and the total value (0)
}, 0); // the }, 0) is important because we want our total value to be 0.
const reviews = [4.5, 4.0, 5.0, 2.0, 1.0, 5.0, 3.0, 4.0, 1.0, 5.0, 4.5, 3.0, 2.5, 2.0];
const reviewsLetter = ['c', 'd', 'f', 'a', 'g', 'a', 'd', 'f', 'e', 'b'];
// 1. Using the reduce function, create an object that// has properties for each review value, where the value// of the property is the number of reviews with that score.// for example, the answer should be shaped like this:// { 4.5: 1, 4: 2 ...}
const countGroupedByReview = reviewsLetter.reduce(groupBy, {});
function groupBy (acc, review){
const count = acc[review] || 0;
return {...acc, [review]: count + 1}}
console.log(countGroupedByReview);
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
// function that takes in the current state, and an action to update it
// you just pass whatever the action you want to perform on the current state
// and it will go ahead and update it
const arr = [2, 10, 40];
const initValue = 0;
const sumWithInitValue = arr.reduce((prevValue, currentValue) => {
return prevValue + currentValue
}, initValue);
console.log(`sum is ${sumWithInitValue}`) // > "sum is 52"