Skip to content

Instantly share code, notes, and snippets.

@kutyel kutyel/reduce.js
Last active Aug 15, 2017

Embed
What would you like to do?
reduce() vs Universe
// reduce() awesomeness
const a = [1, 2, 3, 4, 5, 5, 3]
const b = [{ key: 1, value: 'a' }, { key: 2, value: 'b' }]
const c = [Promise.resolve(), Promise.resolve(), Promise.resolve()]
const d = ['a', 'a', 'a', 'a', 'a']
// Max
a.reduce((x, y) => x > y ? x : y) // > 5
// Min
a.reduce((x, y) => x < y ? x : y) // > 1
// Sum
a.reduce((x, y) => x += y, 0) // > 23
// Unique
a.reduce((x, y) => x.indexOf(y) === -1 ? x.concat(y) : x, []) // > [1, 2, 3, 4, 5]
// Collection to Object
b.reduce((o, v) => (o[v['key']] = v['value'], o), {}) // > Object { 1: "a", 2: "b" }
// Promise chaining
c.reduce((cur, next) => cur.then(next), Promise.resolve()) // > Promise
// Check if all elements in an array are the same
!!d.reduce((x, y) => x === y ? x : null) // > true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.