Last active
September 25, 2019 20:34
-
-
Save iHani/baf68899c247829105b3600ef47c791b to your computer and use it in GitHub Desktop.
Array.reduce() example - JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Array.reducer() | |
* "The reduce() method executes a reducer function (that you provide) on each | |
* element of the array, resulting in a single output value" - MDN Docs | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | |
*/ | |
const arr = [1, 10, 4]; | |
// get the sum of all elements in the array | |
const sumAll = arr.reduce((acc, curr) => acc + curr); | |
console.log(sumAll); // 15 | |
// get the larger number in the array | |
const getLarger = arr.reduce((acc, curr) => acc > curr ? acc : curr); | |
console.log(getLarger); // 10 | |
// extracting the callback reducer function | |
const getLargerReducer = (acc, curr) => acc > curr ? acc : curr; | |
const getLarger = arr.reduce(getLargerReducer); | |
console.log(getLarger); // 10 | |
// Deeper look into the reduce() method. | |
// syntax: arr.reduce(reduceFunction) | |
function reduceFunction(accumulator, currentValue, index, initialValue) { | |
// - accumulator (required): The accumulator accumulates the callback's return values. It is | |
// the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied. | |
// - currentValue (required): The current element being processed in the array. | |
// - index (optional): 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. | |
// - initialValue (optional): The array reduce() was called upon. | |
const value = /* do something */ | |
return value; // `value` will be the `curr` for the next iteration | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment