nonlogos
1/11/2017 - 4:01 PM

All the cool patterns to use with reduce

All the cool patterns to use with reduce

// ---------------------------------
// 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;
  })
// 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']}