Array.Reduce() Flashcards
const array1 = [1, 2, 3, 4]; const reducer =
console.log(array1.reduce(reducer)); // 1 + 2 + 3 + 4
(accumulator, currentValue) => accumulator + currentValue;
const array1 = [1, 2, 3, 4]; const reducer =
console.log(array1.reduce(reducer, 5));
const reducer = (accumulator, currentValue) => accumulator + currentValue;
The reducer function takes four arguments:
1.
2.
3.
4.
Accumulator (acc) Current Value (cur) Current Index (idx) Source Array (src)
arr.reduce(_____(_____, _______[, index[, array]]), [, initialValue])
callback Function
accumulator
Current Value
The __________ adds the callback’s return values. It is the added value previously returned in the last invocation of the callback, or initialValue, if supplied (see below)
accumulator
The current element being processed in the array.
currentValue
the 3 optional values are:
currentIndex
array
initialValue
The current element being processed in the array.
currentValue
The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.
currentIndex
A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initialValue will throw a TypeError.
initialValue
The first time the callback is called, _________ and __________ can be one of two values.
accumulator
currentValue
If initialValue is not provided, reduce() will execute the callback function starting at __________ skipping the first index. If initialValue is provided, it will start at _______
index 1
index 0
var sum = [0, 1, 2, 3].reduce( // code here ) // sum is 6
function (accumulator, currentValue) { return accumulator + currentValue; }
var total = [ 0, 1, 2, 3 ].reduce( // code here );
( accumulator, currentValue ) => accumulator + currentValue
To sum up the values contained in an array of objects, you must supply an_________, so that each item passes through your function.
initialValue
var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) { return \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ },0)
console.log(sum) // logs 6
accumulator + currentValue.x;
var initialValue = 0; var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) { return accumulator + currentValue.x; },initialValue)
WRITE AS A ARROW FUNCTION
( (accumulator, currentValue) => accumulator + currentValue.x
,initialValue
);