reduce深入理解

// map
console.log([1, 2, 3, 4, 5].reduce((a, v) => {
    a.push(v * v);
    return a
},[]));
//filter
console.log([1, 2, 3, 3, 4, 5].reduce((a, v) => {
    if (v > 3) {
        a.push(v)
    }
    return a
}, []));
//max
console.log([1, 2, 3, 4, 5, 6].reduce((a, v) => {
    return Math.max(a, v)
}, []));
//扁平化
console.log([1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5].reduce((a, v) => {
    !a.includes(v) && a.push(v)
    return a
}, []));
//数组扁平化

多个数组交换位置

[1, 2], ['a', 'b']   
// [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

const xProd = (a,b)=>{
  return a.reduce((acc,x)=>{
    return acc.concat(b.map(y=>[x,y]))
  },[])
};

注意为了防止报错  return记得一些要写,第二个就是reduce返回的类型[]

一道比较复杂的题目

# 30s   unzipWith

reduce 对于二维数组的操作
console.log([[1, 10, 100], [2, 20, 200]].reduce(
  (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc)
  ,[[],[],[]]
));
其实比较难理解的点有两点
*  (acc,val)=(fn,acc)
 我们因为知道 let a=(1,3) //3
* reduce 第二个参数 是返回参数的类型,  如果你要返回的类型是
{},{{},{}},[],[[],[]]都是可以的,

这样就好理解啦
const unzipWith = (arr, fn) =>
  arr
    .reduce(
      (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
      Array.from({
        length: Math.max(...arr.map(x => x.length))
      }).map(x => [])
    )
    .map(val => fn(...val)); // 这里不写就会报错,所有注意起始值要写

unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]
关于Array.from不好理解看下面的

Array.from

[['a', 'b'], [1, 2], [true, false]]
变成
[['a', 1, true], ['b', 2, false]]

//////////////////////////////////
const arrays = [['a', 'b'], [1,3, 2], [true, false]];
//先算生成的数组有几项
const a=Array.from({length: Math.max(...arrays.map(v => v.length))});
console.log(a); //[ undefined, undefined, undefined ]
const b=a.map((_,i)=>{
  return Array.from({length:arrays.length},(_,k)=>{
   // k   是array 数组的0,1,2 三次
    return arrays[k][i]
  })
});
console.log(b);

关于reduce很烦的报错

错误实例(直接报错)
arr.reduce((acc,item)=>{
  return acc.push(item.id)
},[])

正确实例
arr.reduce((acc,item)=>{
  return (acc.push(item.id),acc)
},[])  
或者
arr.reduce((acc,item)=>{
  acc.push(item.id)
  return acc
},[])  

.......................................................................................................................................................##############.........................................................................................................................................................................................

posted @ 2019-05-07 18:32  猫神甜辣酱  阅读(600)  评论(0编辑  收藏  举报