js利用reduce对数组中的元素或数组中对象某一属性值求和

1.语法

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

reduce最多可以接收两个参数,第一个参数为必须,是一个函数,此函数实现累加器的作用。第二个参数非必须,是计算的初始值。
如果数组为空,则不会调用reduce中传入的函数。

1.1作为reduce入参的累加器函数,它最多可以有四个入参:

1.total: 计算后的和
2.currentValu:当前项
3.currentIndex:当前项在数组中的索引
4.arr:当前数组
其中totalcurrentValue这两个入参必须存在,另外两个可选。

1.2 关于非必须的初始值

虽然可以只传入累加器函数,不传入语法中initialValue位置的初始值参数,但最好还是传入。否则,当数组为空数组[]的时候,浏览器会报错Reduce of empty array with no initial value,如图:
在这里插入图片描述
加入初始值后:
在这里插入图片描述

2.示例(使用了es6的箭头函数)

普通数组,求和:
let numberArray = [1,2,3,4,5];
let numberSum = numberArray.reduce((sum, curr) => sum + curr);

对象数组,计算学生的年龄和:
let studentsArray = [
	{
		name: '张飞',
		age: 20
	},
	{
		name: '赵云',
		age: 10
	}
];
let ageSum = studentsArray.reduce((ageSum, currStudent) => {
	return ageSum + currentStudent.age;
},0)

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 Array.prototype.reduce() 方法来实现这个功能。具体步骤如下: 1. 遍历数组,对于每个元素,获取需要归类的属性。 2. 在 reduce() 方法中创建一个对象,用于保存归类后的结果。 3. 对于每个元素,检查对象中是否已经存在该属性对应的数组,如果不存在,则创建一个新数组,并将该元素添加到数组中;如果已经存在,则将该元素添加到对应的数组中。 4. 最后,将对象中的转换为数组,即可得到归类后的结果。 下面是一个示例代码: ```javascript const arr = [ { name: 'apple', type: 'fruit' }, { name: 'banana', type: 'fruit' }, { name: 'carrot', type: 'vegetable' }, { name: 'orange', type: 'fruit' }, { name: 'broccoli', type: 'vegetable' }, { name: 'pear', type: 'fruit' }, { name: 'tomato', type: 'vegetable' }, { name: 'pepper', type: 'vegetable' }, { name: 'grape', type: 'fruit' }, { name: 'potato', type: 'vegetable' }, ]; const result = arr.reduce((obj, item) => { if (obj[item.type]) { obj[item.type].push(item); } else { obj[item.type] = [item]; } return obj; }, {}); console.log(result); ``` 输出结果为: ```javascript { fruit: [ { name: 'apple', type: 'fruit' }, { name: 'banana', type: 'fruit' }, { name: 'orange', type: 'fruit' }, { name: 'pear', type: 'fruit' }, { name: 'grape', type: 'fruit' } ], vegetable: [ { name: 'carrot', type: 'vegetable' }, { name: 'broccoli', type: 'vegetable' }, { name: 'tomato', type: 'vegetable' }, { name: 'pepper', type: 'vegetable' }, { name: 'potato', type: 'vegetable' } ] } ``` 在这个示例中,我们将 `arr` 数组中元素按照 `type` 属性进行归类,得到一个包含 `fruit` 和 `vegetable` 两个属性对象。每个属性对应一个数组,包含相同 `type` 属性元素
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值