js数组方法reduce经典用法代码分享(3)

片段十:数据加工器
const reducers = {
 totalInEuros: (state, item) => {
  return state.euros += item.price * 0.897424392;
 },
 totalInYen: (state, item) => {
  return state.yens += item.price * 113.852;
 }
};
const manageReducers = reducers => {
 return (state, item) => {
  return Object.keys(reducers).reduce((nextState, key) => {
   reducers[key](state, item);
   return state;
  }, {})
 }
}
const bigTotalPriceReducer = manageReducers(reducers);
const initialState = { euros: 0, yens: 0 };
const items = [{ price: 10 }, { price: 120 }, { price: 1000 }];
const totals = items.reduce(bigTotalPriceReducer, initialState);
片段十一:对象空值判断
let school = {
 name: 'Hope middle school',
 created: '2001',
 classes: [
  {
   name: '三年二班',
   teachers: [
    { name: '张二蛋', age: 26, sex: '男', actor: '班主任' },
    { name: '王小妞', age: 23, sex: '女', actor: '英语老师' }
   ]
  },
  {
   name: '明星班',
   teachers: [
    { name: '欧阳娜娜', age: 29, sex: '女', actor: '班主任' },
    { name: '李易峰', age: 28, sex: '男', actor: '体育老师' },
    { name: '杨幂', age: 111, sex: '女', actor: '艺术老师' }
   ]
  }
 ]
};
// 常规做法
school.classes &&
school.classes[0] &&
school.classes[0].teachers &&
school.classes[0].teachers[0] &&
school.classes[0].teachers[0].name
// reduce方法
const get = (p, o) => p.reduce((xs, x) => (xs && xs[x] ? xs[x] : null), o);
get(['classes', 0, 'teachers', 0, 'name'], school); // 张二蛋
片段十二:分组
const groupBy = (arr, func) =>
arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => {
 acc[val] = (acc[val] || []).concat(arr[i]);
 return acc;
}, {});
groupBy([6.1, 4.2, 6.3], Math.floor); 
groupBy(['one', 'two', 'three'], 'length'); 
首先通过map计算出所有的键值,然后再根据建值进行归类
片段十三:对象过滤
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});

pick({ a: 1, b: '2', c: 3 }, ['a', 'c']);

根据给出的键值来遍历,比较对象中是否存在相同键值的的值,然后通过逗号表达式把赋值后的对象赋给下一个的初始值