reduce的妙用

2020 M12 22

格式转换

[ "xx1=a", "xx2=b" ] => { "xx1": "a", "xx2": "b" }

["xx1=a", "xx2=b"].reduce((pre, cur) => {
  const [k, v] = cur.split("=");
  pre[k] = v;
  return pre;
}, {});

数组对象去重

var arr=[
    {
      name:'tom',age:18,
    },
    {
      name:'tom',age:18,
    },
    {
      name:'jack',age:18,
    },
]

function keepSingle(arr = [],field='name') {
  let obj = {};
  let res= arr.reduce( (item, next)=> {
    if(!obj[next[field]]){
        obj[next[field]] = true
        item.push(next);
    }
    return item;
  }, []);

  obj=null
  return res
}

redux-compose


function compose(...funcs){

  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a,b)=>(...args)=>{a(b(...args))})

}