JavaScript高阶函数:深入解析reduce()的5种实战应用
一、reduce()基础回顾
reduce()是JavaScript数组中最强大的高阶函数之一,它通过对数组中的每个元素执行一个reducer函数来累积计算结果。基本语法:
array.reduce((accumulator, currentValue, index, array) => {
// 返回累积值
}, initialValue);
二、5个实用案例解析
1. 多维数组扁平化
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]
2. 对象属性分组
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 21 }
];
const groupedByAge = people.reduce((acc, person) => {
const age = person.age;
if (!acc[age]) acc[age] = [];
acc[age].push(person);
return acc;
}, {});
3. 函数管道组合
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const square = x => x * x;
const transform = pipe(add5, multiply2, square);
console.log(transform(5)); // 400
4. 数据统计计算
const sales = [125, 200, 85, 310];
const stats = sales.reduce((acc, val) => {
acc.sum += val;
acc.max = Math.max(acc.max, val);
acc.min = Math.min(acc.min, val);
return acc;
}, { sum: 0, max: -Infinity, min: Infinity });
5. 异步操作顺序执行
const asyncTasks = [
() => fetch('/api/1'),
() => fetch('/api/2'),
() => fetch('/api/3')
];
asyncTasks.reduce(async (prevPromise, currTask) => {
await prevPromise;
return currTask();
}, Promise.resolve());
三、性能优化建议
- 总是提供初始值以避免空数组错误
- 对于大型数组,考虑使用for循环替代
- 避免在reducer中修改原数组
- 复杂操作可以分解为多个reduce步骤