[“b”, “c”,”b”, “c”,”a”, “b”, “c”] 统计每个元素出现的次数
方法1: reduce
const arr = ["b", "c","b", "c","a", "b", "c"]
const newList = arr.reduce((acc,item)=>{
if(item in acc) { // 看item有没有在acc里面
acc[item]++
} else {
acc[item] = 1
}
return acc
},{})
console.log(newList);
输出结果:
![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
const arr = ["b", "c","b", "c","a", "b", "c"]
const obj = {}
arr.forEach(item => {
// if(obj[item]) {
// obj[item] ++
// } else {
obj[item] = 1
// }
obj[item] ? obj[item] ++ : obj[item] =1
})
consloe.log(obj)
输出结果:
![](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)