reduce 方法的简单使用

reduce() 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

今天我们就介绍一下 reduce 的几种简单使用场景。

求数组的累计值

简单数组的累计值获取:

javascript 复制代码
const arr = [12, 3, 7, 34, 6, 22, 15];
const total = arr.reduce((acc, cur) => acc + cur, 0);
console.log(total); // 99

复杂数组的累计值获取:

javascript 复制代码
const people = [
    { name: "Alice", age: 21 },
    { name: "Max", age: 20 },
    { name: "Jane", age: 20 }
];
const ages = people.reduce((acc, cur) => acc + cur.age, 0);
console.log(ages); // 61

按属性对对象进行分组

假设有以下数组:

javascript 复制代码
const people = [
    { name: "Alice", age: 21 },
    { name: "Max", age: 20 },
    { name: "Jane", age: 20 }
];

现要求根据年龄值将上面的数组换换为对象,返回格式为 年龄值:obj。使用 reduce 的实现代码如下:

javascript 复制代码
const ageGroups = people.reduce((acc, cur) => {
    const age = cur.age;
    if (!acc[age]) {
        acc[age] = [];
    }
    acc[age].push(cur.name);
    return acc;
}, {});

console.log(ageGroups);
// {
//     20: ["Max", "Jane"],
//     21: ["Alice"]
// }

展开嵌套数组

我们可以利用 reduce 会累积的特性,逐层展开嵌套数组:

javascript 复制代码
const arr = [
    [0, 1],
    [2, 3],
    [4, 5, 6,7]
];

const flattenArr = arr.reduce((acc, cur) => acc.concat(cur), []);
console.log(flattenArr);
// [0, 1, 2, 3, 4, 5, 6, 7]
相关推荐
NiceCloud喜云21 分钟前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby1 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing1 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩1 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车1 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思2 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫4 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。5 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星5 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒5 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端