Skip to content

Instantly share code, notes, and snippets.

@donchev7
Last active January 6, 2021 12:42
Show Gist options
  • Save donchev7/1afd862278dba0d7facf47d9fa157c45 to your computer and use it in GitHub Desktop.
Save donchev7/1afd862278dba0d7facf47d9fa157c45 to your computer and use it in GitHub Desktop.
Common use cases for JavaScript reduce built in function
//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