统计每个元素出现的次数,常用的数组Api

531 阅读1分钟

aa.webp

前言

在实际工作中会经常遇到需要统计一个元素出现的次数,下面是我总计的几种实际工作中经常使用的Api

1.reduce()方法

<script>
    const val = ["b", "c", "b", "c", "a", "b", "c","d","a"]
    const num = val.reduce((acc,item) =>{
      acc[item] ? acc[item]++ : acc[item]=1
      return acc
    },{})

    // acc:累计器累计回调的返回值;
    // item:数组中正在处理的元素
    console.log(num)// ==> {a: 2,b: 3,c: 3,d: 1}返回值

</script>

2.forEach()方法

<script>
    const arr = ["b", "c", "b", "c", "a", "b", "c","d","a"]

    const obj = {}
    arr.forEach(item =>{  // 循环遍历arr中的每一项
        if(obj[item]){    // 判断元素里面有没有该元素
            obj[item]++   
        }else{
            obj[item] = 1
        }
    })

    console.log(obj) // ==> {a: 2,b: 3,c: 3,d: 1}返回值

</script>