目录
JavaScript 中的 reduce
方法
reduce
方法是 JavaScript 数组的一个非常强大的高阶函数,它允许你对数组中的每个元素执行一个由你提供的 "reducer" 函数(也称为累加器函数),将其结果汇总为单个返回值。这个方法在处理数组数据时非常有用,尤其是当你需要将数组元素通过某种规则汇总成一个值时。
语法
array.reduce((accumulator, currentValue, index, array) => {
// 你的逻辑
}, initialValue);
-
accumulator:累加器,即上一次调用回调时返回的值。
-
currentValue:当前正在处理的元素。
-
index:当前元素的索引(可选)。
-
array:调用
reduce
的数组本身(可选)。 -
initialValue:初始值(可选)。如果没有提供,那么数组的第一个元素会成为累加器的初始值。
示例
1. 数组求和
假设我们有一个数字数组,我们想要计算它们的总和。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // 输出:15
这里,我们从0开始累加数组中的每个数字。
2. 计算数组中所有对象的某个属性总和
如果你有一个用户对象数组,你可能想要计算他们的年龄总和。
const users = [
{ name: 'zs', age: 20 },
{ name: 'ls', age: 25 },
{ name: 'ww', age: 30 },
];
const totalAge = users.reduce((accumulator, user) => accumulator + user.age, 0);
console.log(totalAge); // 输出:75
在这个例子中,我们累加了每个用户的年龄。
3. 数组去重
使用 reduce
来创建一个没有重复数字的数组。
const uniqueNumbers = [1, 2, 2, 3, 4, 4, 5];
const unique = uniqueNumbers.reduce((accumulator, current) => {
if (!accumulator.includes(current)) {
accumulator.push(current);
}
return accumulator;
}, []);
console.log(unique); // 输出:[1, 2, 3, 4, 5]
这里,我们检查累加器数组中是否已经包含了当前的数字,如果没有,就添加进去。
4. 数组扁平化
将一个嵌套的数组扁平化。
const array = [1, [2, [3, [4]], 5]];
const flat = array.reduce((accumulator, currentValue) => {
return accumulator.concat(Array.isArray(currentValue) ? currentValue.flat(Infinity) : currentValue);
}, []);
console.log(flat); // 输出:[1, 2, 3, 4, 5]
在这个例子中,我们递归地扁平化数组,直到所有的嵌套层级都被展开。
5. 数组对象分组
根据对象的某个属性将它们分组。
const people = [
{ name: 'zs', age: 22 },
{ name: 'ls', age: 20 },
{ name: 'ww', age: 25 },
];
const groupedByAge = people.reduce((accumulator, current) => {
if (!accumulator[current.age]) {
accumulator[current.age] = [];
}
accumulator[current.age].push(current.name);
return accumulator;
}, {});
console.log(groupedByAge);
// 输出:{ '20': ['ls'], '22': ['zs'], '25': ['ww'] }
这里,我们根据年龄将用户分组。
6. 数组查找映射
创建一个映射,其中包含数组中每个元素的平方。
const numbers = [1, 2, 3, 4, 5];
const squareMapping = numbers.reduce((accumulator, current) => {
accumulator[current] = current * current;
return accumulator;
}, {});
console.log(squareMapping); // 输出:{ '1': 1, '2': 4, '3': 9, '4': 16, '5': 25 }
在这个例子中,我们为数组中的每个数字创建了一个键值对,键是数字本身,值是它的平方。
7. 统计次数
统计数组中每个元素出现的次数。
const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
const count = numbers.reduce((accumulator, current) => {
accumulator[current] = (accumulator[current] || 0) + 1;
return accumulator;
}, {});
console.log(count); // 输出:{ '1': 1, '2': 2, '3': 3, '4': 4 }
这里,我们创建了一个对象,用来记录每个数字出现的次数。
8. 计算平均值
计算数组中数字的平均值。
const numbers = [1, 2, 3, 4, 5];
const average = numbers.reduce((accumulator, current) => {
accumulator.sum += current;
accumulator.count++;
}, { sum: 0, count: 0 }).sum / (accumulator.count || 1);
console.log(average); // 输出:3
在这个例子中,我们计算了数字的总和和计数,然后计算了平均值。
9. 组合函数
将多个函数组合成一个函数。
const functions = [a => a + 1, a => a * 2, a => a - 3];
const combinedFunction = functions.reduce((accumulator, currentFunction) => {
return currentFunction(accumulator);
}, a => a);
console.log(combinedFunction(5)); // 输出:8
这里,我们通过 reduce
将三个函数组合成了一个函数。