
reduce 是 JavaScript 数组中的一个高阶方法,用于将数组的所有元素“归并”成一个单一的值。它通过依次处理每个元素,并累计一个结果,非常适合用来求和、计数、扁平化数组等场景。
基本语法
arr.reduce(callback(accumulator, current, index, Array), initialValue)
参数说明:
- callback:每次迭代执行的函数,接收四个参数:
- accumulator:累计器,保存上一次调用的返回值
- current:当前正在处理的元素
- index(可选):当前元素的索引
- array(可选):调用 reduce 的原数组
- initialValue(可选):作为第一次调用 callback 时 accumulator 的初始值
如果没有提供 initialValue,reduce 会从数组的第二个元素开始遍历,第一个元素作为 accumulator 的初始值。
常见使用示例
1. 数值求和
最典型的用法是计算数组中所有数字的总和。
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
// 结果:10
2. 计算对象数组的某个属性总和
比如统计购物车商品总价。
const cart = [
{ name: ‘苹果‘, price: 5, count: 2 },
{ name: ‘香蕉’, price: 3, count: 4 }
];
const total = cart.reduce((acc, item) => acc + item.price * item.count, 0);
// 结果:22
3. 数组扁平化
将多维数组转为一维。
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, curr) => acc.concat(curr), []);
// 结果:[1, 2, 3, 4, 5, 6]
4. 统计元素出现次数(分组)
用 reduce 实现类似 groupBy 的功能。
const fruits = [‘apple’, ‘banana’, ‘apple‘, ‘orange’, ‘banana’, ‘apple’];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
// 结果:{ apple: 3, banana: 2, orange: 1 }
5. 按条件分组对象
const people = [
{ name: ‘Alice’, age: 25 },
{ name: ‘Bob’, age: 30 },
{ name: ‘Charlie’, age: 25 }
];
const groupByAge = people.reduce((acc, person) => {
if (!acc[person.age]) {
acc[person.age] = [];
}
acc[person.age].push(person);
return acc;
}, {});
// 按年龄分组
注意事项
reduce 功能强大,但使用时要注意以下几点:
- 如果数组为空且没有提供 initialValue,会抛出错误
- 回调函数必须有返回值,否则后续迭代的 acc 会变成 undefined
- 初始值类型应与最终期望的结果一致,比如累加用数字 0,拼接数组用 [],构建对象用 {}
基本上就这些。掌握 reduce 能让你写出更简洁、函数式风格的代码,尤其适合数据处理场景。关键是理解 accumulator 如何一步步累积结果。不复杂但容易忽略细节。