Last active
January 6, 2021 12:42
-
-
Save donchev7/1afd862278dba0d7facf47d9fa157c45 to your computer and use it in GitHub Desktop.
Common use cases for JavaScript reduce built in function
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
//Summing an Array of Numeric Properties | |
const lineItems = [ | |
{ description: 'Eggs (Dozen)', quantity: 1, price: 3, total: 3 }, | |
{ description: 'Cheese', quantity: 0.5, price: 5, total: 2.5 }, | |
{ description: 'Butter', quantity: 2, price: 6, total: 12 } | |
] | |
const sumReducer = (sum, val) => sum + val | |
lineItems.map(li => li.total).reduce(sumReducer, 0) | |
//Find the Maximum Value | |
const dates = [ | |
'2019/06/01', | |
'2018/06/01', | |
'2019/09/01', // This is the most recent date. Find it. | |
'2018/09/01' | |
].map(v => new Date(v)) | |
const maxDate = dates.reduce((max, d) => d > max ? d : max, dates[0]) | |
//Grouping Values | |
const characters = [ | |
{ name: 'Jean-Luc Picard', age: 59 }, | |
{ name: 'Will Riker', age: 29 }, | |
{ name: 'Deanna Troi', age: 29 } | |
] | |
const reducer = (map, val) => { | |
if (map[val] == null) { | |
map[val] = 1 | |
} else { | |
++map[val] | |
} | |
return map | |
} | |
characters.map(char => char.age).reduce(reducer, {}) | |
//Promise chaining | |
const functions = [ | |
async () => 1, | |
async () => 2, | |
async () => 3, | |
] | |
// Chain the function calls in order, starting with an empty promise. | |
// In the end, `res` is equivalent to | |
// `Promise.resolve().then(fn1).then(fn2).then(fn3)` | |
const res = await functions.reduce((promise, fn) => promise.then(fn), Promise.resolve()) | |
console.log(res) //3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment