reduce实现js
使用 reduce 实现数组求和
reduce 可以对数组元素进行累加求和。初始值设为 0,回调函数将当前值累加到总和。
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 输出: 10
使用 reduce 实现数组扁平化
通过递归或直接拼接子数组,reduce 可将多维数组扁平化为一维数组。
const nestedArray = [1, [2, [3, [4]]]];
const flatten = (arr) =>
arr.reduce((flat, item) =>
flat.concat(Array.isArray(item) ? flatten(item) : item), []);
console.log(flatten(nestedArray)); // 输出: [1, 2, 3, 4]
使用 reduce 统计元素出现次数
通过初始化一个空对象,reduce 可以统计数组中各元素的出现频率。
const fruits = ['apple', 'banana', 'apple', 'orange'];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // 输出: {apple: 2, banana: 1, orange: 1}
使用 reduce 实现数组去重
利用 reduce 和 includes 方法,可以过滤掉重复元素。
const duplicates = [1, 2, 2, 3, 4, 4];
const unique = duplicates.reduce((acc, num) =>
acc.includes(num) ? acc : [...acc, num], []);
console.log(unique); // 输出: [1, 2, 3, 4]
使用 reduce 实现对象属性分组
根据对象的某个属性值,reduce 可以将对象数组分组为键值对结构。
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Bob', age: 21 },
{ name: 'Charlie', age: 22 }
];
const grouped = people.reduce((groups, person) => {
const key = person.age;
groups[key] = groups[key] || [];
groups[key].push(person);
return groups;
}, {});
console.log(grouped);
// 输出: {21: [{name: 'Alice', age: 21}, {name: 'Bob', age: 21}], 22: [{name: 'Charlie', age: 22}]}
使用 reduce 实现管道函数组合
通过 reduce 可以将多个函数依次组合,形成管道式调用。

const pipe = (...fns) => (x) => fns.reduce((v, fn) => fn(v), x);
const add1 = x => x + 1;
const double = x => x * 2;
const process = pipe(add1, double);
console.log(process(3)); // 输出: 8 (3 + 1 = 4, 4 * 2 = 8)






