​reduce​​ 方法在数组的每个元素上执行提供的回调函数迭代器。它传入前一个元素计算的返回值,结果是单个值,它是在数组的所有元素上运行迭代器的结果。

迭代器函数逐个遍历数组的元素,在每一步中,迭代器函数将当前数组值添加到上一步的结果中,直到没有更多元素要添加。

语法

参数包含回调函数和可选的初始值,如下:

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

回调函数

回调函数接受一下四个参数:

  • ​accumulator​​:前一个回调函数产生的前一个值,即累计器
  • ​currentValue​​:数组遍历的当前元素,即当前值
  • ​currentIndex​​:当前索引
  • ​sourceArray​​:原数组

初始值

初始值参数是可选的,它是第一次调用回调时将前一个值初始化为的值。如果未指定初始值,则将前一个值初始化为初始值,将当前值初始化为数组中的第二个值。

​reduce()​​​ 方法是一种有价值的方法,在某些情况下,它可能会节省时间或减少编码的行数。在本文中,将展示 JavaScript 中 ​​reduce()​​ 方法的六个实例。

关于日常项目中可能会遇到的代码片段,可以参阅专栏《碎片时间学习Javascript代码》,里面包含更多的代码实例。

1. 数组求和

const sum = (array) =>
array.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum([1, 2, 3, 45])); // 51

2. 数组展平

使用 ​​reduce()​​,可以很容易将多维数组转换为一维集合。

const flatten = (array) =>
array.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
});
console.log(
flatten([
[2, 3, 5],
[1, 2, 4],
[8, 5, 5],
])
);

3. 创建Pipeline

此外,可以减少函数以及数字和字符串,假设有一系列数学函数。例如,有以下功能:

function increment(input) {
return input + 1;
}
function decrement(input) {
return input - 1;
}
function double(input) {
return input * 2;
}

此外,希望对订单使用 ​​increment​​​、​​double​​​ 和 ​​decrement​​​。因此,可以为此创建管道。然后,可以将它与 ​​reduce()​​ 一起使用。

const pipeline = [increment, double, decrement];

const funPipeline = (funcs, value) =>
funcs.reduce(function (total, func) {
return func(total);
}, value);
console.log(funPipeline(pipeline, 10)); // 21

4. 数组重复项计算

例如,有一个字符串数组,它们是一个颜色数组,使用 ​​reduce()​​ 将其中每种颜色的重复次数计算出来,如下:

const colors = [
"green",
"red",
"red",
"yellow",
"red",
"yellow",
"green",
"green",
];

const countToMap = (array) =>
array.reduce((prev, apple) => {
if (prev[apple] >= 1) prev[apple]++;
else prev[apple] = 1;
return prev;
}, {});

console.log(countToMap(colors)); // { green: 3, red: 3, yellow: 2 }

5. 数组中出现奇数次的整数

使用 ​​reduce()​​ 来查找在给定数组中出现奇数次的整数,如下:

const findOdd = (a) => a.reduce((a, b) => a ^ b);
console.log(findOdd([1, 2, 2, 1])); // 0
console.log(findOdd([1, 2, 2, 1, 2, 3, 3])); // 2

6. 查找数组的最大子数组和

使用此函数,可以找到给定数组的最大子数组和,如下:

const maxSequence = (a, sum = 0) =>
a.reduce((max, v) => Math.max((sum = Math.max(sum + v, 0)), max), 0);
console.log(maxSequence([1, 2, 3, 4])); // 10

总结

了解 JavaScript 中一些内置高阶函数的用例,可以帮助提高编码技能。