JS中reduce用法-数组求和

reduce函数介绍

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 对于空数组是不会执行回调函数的。参数如下:

arr.reduce([callback, initialValue])

在这里插入图片描述
可以看到这是一个求和,或者统计有关的函数,那么可以得出以下用途。
基础数据:

const baseData = [
       {age: 10, name: '小明'},
       {age: 15, name: '小黄'},
       {age: 18, name: '小王'},
       {age: 18, name: '小白'},
       {age: 21, name: '小陈'}
]

1. 数组求和

求出数组中所有年龄的和:

// 方法一
baseData.reduce((total, currentValue) => total + currentValue.age, 0);
// 方法二
baseData.reduce((previousValue, currentValue, index) => {
  console.log(index)
  if(typeof previousValue === 'number') {
    return previousValue + currentValue.age
  } else {
    return previousValue.age + currentValue.age
  }
})

2. 数组去重

去掉数组中年龄重复的数据

let resultArr = baseData.reduce((result, currentValue, index) => {
  	if (!result.find(item => item.age === currentValue.age)) {
    		result.push(currentValue)
        }
    return result
  }, [])
  console.log(resultArr, 'result')

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

const arraySum = (arr, val) => arr.reduce((acc, cur) => {
    return cur == val ? acc + 1 : acc + 0
}, 0);

let arr = [ 0, 1, 3, 0, 2, 0, 2, 3 ]
console.log(arraySum(arr, 0)) // 数组arr中 0 元素出现的次数为3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值