JavaScript reduce 的 10 个高阶用法合集
一次遍历,重塑数组思维
在大多数人的印象里, reduce 只是“求和函数”。 但在真实工程中, reduce 是 数据结构变换的瑞士军刀 。
熟练使用它,你可以少写一半循环代码,并且写出更具表达力的数据处理逻辑。
这篇文章整理 10 个生产中高频出现的 reduce 技巧 : 去重、扁平化、分组、树结构生成、索引映射等,一篇打通。
1. 求和(基础但不可缺席)
const total = list.reduce((sum, item) => sum + item.count, 0);所有高级玩法,本质都是「累积器 acc」。
2. 数组去重
const arr = [1,2,2,3,3,3];
const result = arr.reduce((acc, item) => {
if (!acc.includes(item)) acc.push(item);
return acc;
}, []);
console.log(result); // [1,2,3]更高性能版本(适合大数组):
const result = [...arr.reduce((set, item) => set.add(item), new Set())];3. 扁平化数组(flat 替代方案)
const arr = [1, [2, [3, 4]], 5];
function flat(arr) {
return arr.reduce((acc, item) => {
return acc.concat(Array.isArray(item) ? flat(item) : item);
}, []);
}
flat(arr); // [1,2,3,4,5]面试经典题,但在处理不规则接口数据时也很常见。
4. 数组转对象索引映射
const list = [
{ id: 101, name: 'A' },
{ id: 102, name: 'B' }
];
const map = list.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {});
console.log(map[102]); // {id:102,name:'B'}📌 React 状态查找优化必备技巧
5. 分组聚合
const list = [
{ type: 'A', count: 2 },
{ type: 'B', count: 3 },
{ type: 'A', count: 4 }
];
const grouped = list.reduce((acc, item) => {
(acc[item.type] ||= []).push(item);
return acc;
}, {});生成:
{
A: [{…},{…}],
B: [{…}]
}6. 分组统计汇总
const result = list.reduce((acc, item) => {
acc[item.type] = (acc[item.type] || 0) + item.count;
return acc;
}, {});📊 报表统计、图表数据整理的核心写法。
7. 构建树形结构
接口常见返回:
const list = [
{ id: 1, parent: null },
{ id: 2, parent: 1 },
{ id: 3, parent: 1 }
];生成树:
const tree = list.reduce((acc, item, _, arr) => {
item.children = [];
acc[item.id] = item;
if (item.parent === null) acc.root = item;
else acc[item.parent].children.push(item);
return acc;
}, {}).root;📌 后台管理系统菜单树、权限树必用。
8. 统计元素出现次数
const arr = ['a','b','a','c','b','a'];
const countMap = arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});结果:
{ a:3, b:2, c:1 }9. 多字段组合转换
把接口字段拍平成前端需要结构:
const list = [
{ id:1, name:'Apple', price:3 },
{ id:2, name:'Orange', price:2 }
];
const result = list.reduce((acc, item) => {
acc.push({
label: item.name,
value: item.id,
cost: item.price
});
return acc;
}, []);📌 UI Select / Table 常见数据整形操作。
10. 串行执行 Promise 队列
const tasks = [
() => fetch('/a'),
() => fetch('/b'),
() => fetch('/c')
];
tasks.reduce((p, task) => {
return p.then(task);
}, Promise.resolve());📌 当你需要 顺序请求接口 时非常优雅。
reduce 的本质思维
所有案例都符合一个模型:
输入数组 → 累积器 acc → 输出任意结构所以 reduce 并不是“求和函数”, 而是:
数组 → 任意数据结构的转换器
工程实践建议
数据整形 → reduce
分组统计 → reduce
索引映射 → reduce
状态派生计算 → reduce + useMemo / computed
超大数组 → 避免多次遍历
最后总结
如果说 map 是「一对一变换」 filter 是「筛选保留」
那么:
reduce = 自定义数组变形引擎
掌握 reduce,意味着你已经具备了 前端数据建模与整形的核心能力 。
发布评论
发布评论前请先 登录。
评论列表 0

暂无评论



