Skip to content

Instantly share code, notes, and snippets.

@nonlogos
Last active January 11, 2017 20:26
Show Gist options
  • Save nonlogos/5495704932b5d9fd75ce2fff3ecaf789 to your computer and use it in GitHub Desktop.
Save nonlogos/5495704932b5d9fd75ce2fff3ecaf789 to your computer and use it in GitHub Desktop.
All the cool patterns to use with reduce
// I'm trying to merge the methods of two objects into one such that an array of methods results for each property in the parent object:
//obj1 = {"prop1":"method1","prop2":"method2"}
//obj2 = {"prop1":"method3","prop2":"method4"}
//Desired output:
//obj1 = {"prop1":["method1","method3"],"prop2":["method2","method4"]}
var merge = function(/*...objs*/) {
return [].reduce.call(arguments, function(acc, x) {
Object.keys(x).forEach(function(k) {
acc[k] = (acc[k]||[]).concat([x[k]])
})
return acc
},{})
}
var obj1 = {prop1: "method1", prop2: "method2"}
var obj2 = {prop1: "method3", prop2: "method4"}
console.log(merge(obj1, obj2))
//^
// {prop1: ['method1', 'method3'],
// prop2: ['method2', 'method4']}
// ---------------------------------
// sum
const arrayPeople = [{
name: 'joe',
job: 'programmer',
age: 25,
}, {
name: 'bob',
job: 'plumber',
age: 30,
}],
average = arrayPeople.reduce((acc, curr) => {
return acc + curr.age;
}, 0)/arrayPeople.length
// or we can also use map to grab the age values and then apply reduce to get the sum
const average = arrayPeople.
map(person => {
return person.age
}).
reduce((acc, curr) => {
return acc + curr;
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment