reduce的常用方法( 最好设置默认值 )

news/2024/7/15 18:06:21 标签: 前端, javascript, react.js, 前端框架

 

目录

参数

1. 数组求和、求乘积

2. 累加数组中对象的值

3. 计算数组中每个元素出现的次数

4. 数组去重

5. 二维数组变一维数组

6. 将多维数组转化为一维

7. 根据属性把对象分类


参数
参数描述
total必需。initialValue,或函数先前返回的值。
currentValue必需。当前元素的值。
index 可选。当前元素的数组索引。
arr  可选。当前元素所属的数组对象
initialValue

可选。作为初始值传递给函数的值。

javascript">array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

注释:对没有值的数组元素,不执行 reduce() 方法。
注释:reduce() 方法不会改变原始数组。

1. 数组求和、求乘积
javascript">let num = [1, 2, 3, 4, 5]
let result1 = num.reduce((sum, n) => sum + n, 0)
console.log(result1); // 15
 
// let result2 = num.reduce((sum, n) => sum * n)
let result2 = num.reduce((sum, n) => sum * n, 1)
console.log(result2); // 120

2. 累加数组中对象的值
javascript">let numObj = [{n: 1}, {n: 2}, {n: 3}, {n: 4}, {n: 5}]
let result3 = numObj.reduce((sum, obj) => sum + obj.n, 0)
console.log(result3); // 15

3. 计算数组中每个元素出现的次数
javascript">let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'red']
let countColor = colors.reduce(function(all, color){
    if(color in all) {
        all[color]++;
    } else {
        all[color] = 1;
    }
    return all;
}, {});
console.log(countColor); // {blue: 1, green: 1, indigo: 1, orange: 1, purple: 1, red: 2, yellow: 1}
4. 数组去重
javascript">let arr = [1, 2, 3, 4, 4, 1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
        return pre.concat(cur)
    }else{
        return pre
    }
},[])
console.log(newArr); // [1, 2, 3, 4]
5. 二维数组变一维数组
javascript">let twoArray = [[0, 1], [2, 3], [4, 5]]
let oneArray = twoArray.reduce((arr, val) => arr.concat(val), [])
console.log(oneArray);  // [0, 1, 2, 3, 4, 5]
6. 将多维数组转化为一维
javascript">let moreArr = [[0, 1], [2, 3], [4,[5,6,7]]]
const resultArr = function(moreArr){
      return moreArr.reduce((pre,cur) => pre.concat(Array.isArray(cur) ? resultArr(cur) : cur), [])
}
console.log(resultArr(moreArr)); // [0, 1, 2, 3, 4, 5, 6, 7]
7. 根据属性把对象分类
javascript">let peopleInfo = [
    {name: 'aaa', age: 15, sex: '男'},
    {name: 'bbb', age: 16, sex: '女'},
    {name: 'ccc', age: 15, sex: '女'}
]
function groupBy(objectArray, property) {
    return objectArray.reduce((resultObj, obj) => {
        var key = obj[property]
        if(!resultObj[key]) {
        	resultObj[key] = []
        }
        resultObj[key].push(obj)
        return resultObj;
    }, {})
}
let peopleAgeGroup = groupBy(peopleInfo, 'age')
console.log(peopleAgeGroup); // {15: [{name: "aaa", age: 15, sex: "男"}, {name: "ccc", age: 15, sex: "女"}],16: [{name: "bbb", age: 16, sex: "女"}]}
let peopleSexGroup = groupBy(peopleInfo, 'sex')
console.log(peopleSexGroup); // {男: [{name: "aaa", age: 15, sex: "男"}], 女: [{name: "bbb", age: 16, sex: "女"}, {name: "ccc", age: 15, sex: "女"}]}

 http://t.csdnimg.cn/Oe0x4


http://www.niftyadmin.cn/n/5114767.html

相关文章

html web前端,点击发送验证码,按钮60秒倒计时

html web前端&#xff0c;点击发送验证码&#xff0c;按钮60秒倒计时 eaca39b57a49d39f6c9e2f49f2559e9a.jpg <!DOCTYPE html> <html><head><meta http-equiv"Content-Type" content"text/html; charsetutf-8" /><title><…

js 节流函数封装示例

<!DOCTYPE html> <html><head><meta charset"utf-8"><title>节流函数示例</title><divstyle"width: 400px;height: 400px;background-color: red;font-size: 30px; text-align: center; line-height: 200px;">&…

位操作符^以及正负数在计算机中的存储

(数据是怎么在计算机中存储的)​ 正数和负数在内存中都是以补码的形式存储的&#xff0c;但不同的是正数的原码&#xff0c;补码&#xff0c;反码都是相同的&#xff0c;而负数的原码&#xff0c;补码和反码是不同的。 负数的原码&#xff0c;补码&#xff0c;反码之间存在什么…

【从0到1设计一个网关】自研网关的设计要点以及架构设计

文章目录 请求的流程架构设计设计要点项目架构流程设计请求的流程 一个HTTP请求发送到网关并完成整个生命周期通常包括以下步骤: 客户端请求: 请求始于客户端,客户端通过HTTP请求(例如GET、POST等)发送请求到API网关的入口点。 API网关接收: API网关作为请求的第一个接…

echarts实现柱状重叠展示(背景是浅白色壮壮图,数据采用其他柱状图展示)

重点 {name: ,type: bar,barWidth: 30,z: "-1",barGap: -100%, itemStyle: {color: rgba(255,255,255,0.1)},data: [100, 100, 100, 100, 100, 100]},initProgressChart() {this.progressChart echarts.init(document.getElementById(progressChart))var option {…

【EtherCAT】二、下载并使用TwinCAT

下载并使用TwinCAT 引言介绍下载安装TwinCAT使用 更多精彩&#xff0c;欢迎关注 引言 TwinCAT是一款由德国Beckhoff Automation开发的工业自动化控制软件。它被广泛用于工厂自动化、过程控制、机器控制以及其他自动化领域。 而这里我们主要使用TwinCAT模拟ECAT主站。本文将介绍…

【VisualStudio】error C2760: 语法错误: 意外的令牌“标识符”,预期的令牌为“类型说明符”

相关参考&#xff1a; 配置适用于 Windows XP 的程序 | Microsoft Learn VS2017应用在XP系统上运行_vs2017 xp-CSDN博客 VS2019怎样编译出可以在WinXP上运行的exe&#xff1f;_vs2019 xp-CSDN博客 在 vs2017 编译报错如下&#xff1a; c:\program files (x86)\microsoft sdks\…

“揭秘!京东关键字搜索接口,轻松获取海量精准商品信息!“

京东关键字搜索接口是一种应用程序接口&#xff0c;它允许开发者通过使用特定的关键词或短语来查询京东的商品数据库&#xff0c;获取相关的商品信息和销售数据。 通过这个接口&#xff0c;企业和个人可以快速、准确地获取他们所需的商品信息&#xff0c;进而提高销售和客户满…