计算一个元素在数组中出现的次数

276 阅读1分钟

使用数组的 reduce 方法完成这个功能

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const arr = ['b', 'c', 'b', 'c', 'a', 'b', 'c']
      // 你的代码 ...
      const obj = arr.reduce((sum, item) => (sum[item] ? sum[item]++ : (sum[item] = 1), sum), {})
      console.log(obj) // ==> {b: 3, c: 3, a:1}
    </script>
  </body>
</html>

这个 reduce 方法的使用在上上上篇博客数组 API 中有总结,请参考