[“b”, “c”,”b”, “c”,”a”, “b”, “c”] 统计每个元素出现的次数

方法1: reduce

  1. const arr = ["b", "c","b", "c","a", "b", "c"]
  2. const newList = arr.reduce((acc,item)=>{
  3. if(item in acc) { // 看item有没有在acc里面
  4. acc[item]++
  5. } else {
  6. acc[item] = 1
  7. }
  8. return acc
  9. },{})
  10. console.log(newList);

输出结果:

  1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/21762447/1624541212940-4ab41f57-138f-4ae6-9471-dd65f5b08b15.png#clientId=ud7ffe11d-129b-4&from=paste&height=141&id=u8abc88d7&margin=%5Bobject%20Object%5D&name=image.png&originHeight=141&originWidth=281&originalType=binary&ratio=1&size=6176&status=done&style=none&taskId=ubffbc4a9-7fd6-41ed-a932-269275d5896&width=281)

方法2: forEach

  1. const arr = ["b", "c","b", "c","a", "b", "c"]
  2. const obj = {}
  3. arr.forEach(item => {
  4. // if(obj[item]) {
  5. // obj[item] ++
  6. // } else {
  7. obj[item] = 1
  8. // }
  9. obj[item] ? obj[item] ++ : obj[item] =1
  10. })
  11. consloe.log(obj)

输出结果:

  1. ![](https://cdn.nlark.com/yuque/0/2021/png/21762447/1624541212940-4ab41f57-138f-4ae6-9471-dd65f5b08b15.png#from=url&id=aNIar&margin=%5Bobject%20Object%5D&originHeight=141&originWidth=281&originalType=binary&ratio=1&status=done&style=none)