js reduce实现
使用 reduce 实现数组求和
reduce 方法通过遍历数组,将元素累积为单个值。以下是一个简单的数组求和示例:
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出: 10
accumulator:累积值,初始值为0(第二个参数)。currentValue:当前处理的数组元素。
使用 reduce 实现数组扁平化
通过 reduce 可以将多维数组扁平化为一维数组:

const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattened = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattened); // 输出: [1, 2, 3, 4, 5, 6]
- 初始值为空数组
[]。 concat方法将当前数组与累积数组合并。
使用 reduce 统计元素出现次数
reduce 可以统计数组中各元素的出现次数:

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // 输出: { apple: 3, banana: 2, orange: 1 }
- 初始值为空对象
{}。 - 每次遍历时更新当前元素的计数。
使用 reduce 实现管道函数
通过 reduce 可以将多个函数组合成一个管道:
const double = x => x * 2;
const square = x => x * x;
const functions = [double, square];
const result = functions.reduce((acc, fn) => fn(acc), 5);
console.log(result); // 输出: 100 (5 → 10 → 100)
- 初始值为
5。 - 依次应用
double和square函数。
使用 reduce 实现对象转换
reduce 可以将数组转换为特定结构的对象:
const people = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const peopleById = people.reduce((acc, person) => {
acc[person.id] = person;
return acc;
}, {});
console.log(peopleById);
// 输出: { 1: { id: 1, name: 'Alice' }, 2: { id: 2, name: 'Bob' }, 3: { id: 3, name: 'Charlie' } }
- 初始值为空对象
{}。 - 将数组元素以
id为键存入对象。






