我喜欢的Array.prototype.reduce登场

1.reduce的简述

reduce() 方法接受一个数组作为输入值并返回一个值,这点比起其他方法来说非常的有趣。reduce 接受一个回调函数,回调函数参数包括一个累计器【accumulator】(数组每一段的累加值,它会像雪球越滚越大),当前值【currentValue】,和索引【currentIndex】, 和当前数组【array】。reduce 也接受一个初始值【initalval】作为第二个参数:

let finalVal = oldArray.reduce(
  (accumulator, currentValue, currentIndex, array) => {
    // ...
  },
  initalval
)
  • Accumulator (acc) (累计器)
  • Current Value (cur) (当前值)
  • Current Index (idx) (当前索引)
  • Source Array (src) (源数组)
  • initalval (init) 初始值
2.用reduce来炒菜

来看一张有趣的图(如下是一张炒菜的图)

在这里插入图片描述
在这里插入图片描述

来写一个炒菜函数和一个作料清单:

// 菜品数组
const ingredients = ['wine', 'tomato', 'onion', 'mushroom']
// 炒菜函数
const cook = (ingredient) => {
  return `cooked ${ingredient}`
}

我们继续来调个调味汁

const wineReduction = ingredients.reduce((sauce, item) = {
	return sauce += cook(item) + ', '
}, '')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "

初始值(这个例子中的 ‘’)很重要,它决定了第一个作料能够进行烹饪。这里输出的结果不太靠谱,自己炒菜时要当心。下面的例子就是我要说到的情况:

const wineReduction = ingredients.reduce((sauce, item) = {
	return sauce += cook(item) + ', '
})
// wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "

最后,确保新字符串的末尾没有额外的空白,我们可以传递索引和数组来执行转换:

const wineReduction = ingredients.reduce((sauce, item, index, array)=>{
    sauce += cook(item)
    if(index < array.length - 1) {
        sauce += ', '
    }
    return sauce;
}, '')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

记住这个方法的简单办法就是回想你怎么做调味汁:把多个作料归约到单个。

3.reduce转换为其他数组函数
reduce -> map

map 方法接收一个回调函数,函数内接收三个参数,当前项、索引、原数组,返回一个新的数组,并且数组长度不变。知道了这些特征之后,我们用 reduce 重塑 map

const testArr = [1, 2, 3, 4]
Array.prototype.reduceMap = function(callback) {
  return this.reduce((acc, cur, index, array) => {
    const item = callback(cur, index, array)
    acc.push(item)
    return acc
  }, [])
}
testArr.reduceMap((item, index) => {
  return item + index
})
// [1, 3, 5, 7]

Array 的原型链上添加 reduceMap 方法,接收一个回调函数 callback 作为参数(就是 map 传入的回调函数),内部通过 this 拿到当前需要操作的数组,这里 reduce 方法的第二个参数初始值很关键,需要设置成一个 [] ,这样便于后面把操作完的单项塞入 acc 。我们需要给 callback 方法传入三个值,当前项、索引、原数组,也就是原生 map 回调函数能拿到的值。返回 item 塞进 acc,并且返回 acc ,作为下一个循环的 acc(贪吃蛇原理)。最终 this.reduce 返回了新的数组,并且长度不变。

reduce -> forEach
const testArr = [1, 2, 3, 4]
Array.prototype.reduceForEach = function(callback) {
  this.reduce((acc, cur, index, array) => {
    callback(cur, index, array)
  }, [])
}

testArr.reduceForEach((item, index, array) => {
  console.log(item, index)
})
// 1234
// 0123

只要看得懂 reduce -> map ,转 forEach 只是改改结构的问题, 所以非常的简单。

reduce -> filter
const testArr = [1, 2, 3, 4]
Array.prototype.reduceFilter = function (callback) {
   return this.reduce((acc, cur, index, array) => {
    if (callback(cur, index, array)) {
      acc.push(cur)
    }
    return acc
  }, [])
}
testArr.reduceFilter(item => item % 2 == 0) // 过滤出偶数项。
// [2, 4]

filter 方法中 callback 返回的是 Boolean 类型,所以通过 if 判断是否要塞入累计器 acc ,并且返回 acc 给下一次对比。最终返回整个过滤后的数组。

reduce -> find
const testArr = [1, 2, 3, 4];
const testObj = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
Array.prototype.reduceFind = function (callback) {
  return this.reduce((acc, cur, index, array) => {
    // 只要符合条件一次就行
    if (callback(cur, index, array)) {
      // acc instanceof Array 这步是避免重新赋值的关键
      if (acc instanceof Array && acc.length === 0) {
        acc = cur;
      }
    }
    // 循环到最后若acc还是数组,且等于0, 代表没有找到想要的项,则acc=undefined
    if (
      index === array.length - 1 &&
      acc instanceof Array &&
      acc.length === 0
    ) {
      acc = undefined;
    }
    return acc;
  }, []);
};
testArr.reduceFind((item) => item % 2 == 0); // 2
testObj.reduceFind((item) => item.a % 2 == 0); // {a: 2}
testObj.reduceFind((item) => item.a % 9 == 0); // undefined

find 方法中 callback 同样也是返回 Boolean 类型,返回你要找的第一个符合要求的项。你不知道操作的数组是对象数组还是普通数组,所以这里只能直接覆盖 acc 的值,找到第一个符合判断标准的值就不再进行赋值操作。

reduce -> some
Array.prototype.reduceSome = function (callback) {
  return this.reduce((acc, cur, index, array) => {
    // 只要符合条件一次就行
    if (callback(cur, index, array)) {
      if (acc instanceof Array && acc.length === 0) {
        acc = true;
      }
    }
    // 循环到最后若acc还是数组,且等于0, 代表没有找到想要的项,则acc=undefined
    if (
      index === array.length - 1 &&
      acc instanceof Array &&
      acc.length === 0
    ) {
      acc = false;
    }
    return acc;
  }, []);
};

testArr.reduceSome((item) => item % 2 == 0); // true
testObj.reduceSome((item) => item.a % 2 == 0); // true
testObj.reduceSome((item) => item.a % 9 == 0); // false

somefind非常的类似, 都是找到符合条件的就行,只不过find是找到对应的索引,而some找到后直接返回true

reduce -> every
Array.prototype.reduceEvery = function (callback) {
  return this.reduce((acc, cur, index, arr) => {
    // 只要有一个数据项条件不满足就返回false
    if (!callback(cur, index, arr)) {
      acc = false;
    }
    return acc;
  }, true);
};

testArr.reduceEvery((item) => item > 0); // true
testArr.reduceEvery((item) => item > 2); // false

every 必须是所有都要符合条件才行, 就像上面回调中显示, 只要有一个不符合条件就会返回false

4.reduce实用工具

在我们平时工作中可能大家对于reduce的热情并不是很高,但是只要掌握了reduce,在我们写业务的时候会起到事半功倍的效果。

二维数组转一维数组
const testArr2 = [
  [1, 2],
  [3, 4],
  [5, 6],
  [7, 8],
];
testArr2.reduce((acc, cur) => {
  return acc.concat(cur);
}, []); // [1, 2, 3, 4, 5, 6, 7, 8 ]

主要是通过concat函数将数组打散,然后合并。

多维数组转一维数组
const testArrs = [
  -1,
  0,
  [1, 2, 3, [4, 5, 6]],
  [7, 8, 9, [10, 11, [12, [13]]]],
  [14, [15]],
];
function formatArr(arrs) {
  if (!Array.isArray(arrs)) {
    throw new Error(arrs + ' is not array');
  }
  return arrs.reduce((acc, cur) => {
    if (Array.isArray(cur)) {
      // 这步就是核心
      return acc.concat(formatArr(cur));
    } else {
      return acc.concat(cur);
    }
  }, []);
}
formatArr(testArrs); //[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

acc.concat(formatArr(cur))这句代码是核心,如果是内部嵌套数组,采用递归的方式和cancat配套进行操作。

计算数组中元素出现的个数
const testArrCount = [
  1, 3, 4, 1, 3, 2, 9, 8, 5, 3, 2, 0, 12, 10, 1, 4, 5, 6, 2, 3, 4, 5, 6,
];
testArrCount.reduce((acc, cur) => {
  // 写法一
  // if (!(cur in acc)) {
  //   acc[cur] = 1;
  // } else {
  //   acc[cur] += 1;
  // }
  // 写法二
  if (!acc.hasOwnProperty(cur)) {
    acc[cur] = 1;
  } else {
    acc[cur] += 1;
  }
  return acc;
}, {}); //{'0': 1,'1': 3,'2': 3,'3': 4,'4': 3,'5': 3,'6': 2,'8': 1,'9': 1,'10': 1,'12': 1}

里面判断有两种写法, 写法一中的in是可以直接让对象遍历的,而写法二中的hasOwnProperty是判断对象中有没有属于自己的属性, 两种都可以。都是累计器 acc 中是否含有 cur 属性,如果没有默认赋值 1,如果已经存在 += 1 累加一次。在实际的开发业务中,这个方法非常常用,变种也很多。比如给你一个账单列表(项与项之间的消费类型有相同情况),让你统计账单列表中各个消费类型的支出情况,如 购物学习转账 等消费类型的支出情况。这就用到了上述方法,去通过归类。如下代码。

按属性给数组分类
const bills = [
  { type: 'shop', momey: 223 },
  { type: 'study', momey: 341 },
  { type: 'shop', momey: 821 },
  { type: 'transfer', momey: 821 },
  { type: 'study', momey: 821 }
];
bills.reduce((acc, cur) => {
  // 如果不存在这个键,则设置它赋值 [] 空数组
  if (!acc[cur.type]) {
    acc[cur.type] = [];
  }
  acc[cur.type].push(cur)
  return acc
}, {})
数组去重
testArrCount.reduce((acc, cur) => {
  if (!acc.includes(cur)) {
    acc.push(cur);
  }
  return acc;
}, []);
// [1, 2, 3, 4, 5, 6, 7]

上述代码逻辑,就是逐一对比,通过 includes 方法检查累计器里是否已经有当前项。

求最大值或最小值
const testArr = [
  { age: 20 },
  { age: 21 },
  { age: 22 }
]
testArr.reduce((acc, cur) => {
  if (!acc) {
    acc = cur
    return acc
  }
  if (acc.age < cur.age) {
    acc = cur
    return acc
  }
  return acc
}, 0)
// {age: 22}

第一次没有对比直接 acc 赋值 cur ,后面进入对比判断,如果 accage 属性小于 curage 属性,重制 acc 。相等的话默认返回 acc

5总结

reduce的用法还非常多,当遇到复杂数组操作时候,它就可以派上用场了,未来,我也会继续对此部分继续做补充!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值