# 在想一个js算法，如何算出数组所有项的出现次数

``````比如 var arr = [1, 2, 3, 1, 5, 8, 2, 9, 9, 2, 2, 2, 3];

7 个回答
ars_qu
• 1.6k

#### 第一种 obj 记录出现次数

``````var obj = {};
for(var i=0;i<arr.length;i++)
obj[arr[i]] = !obj[arr[i]]?1:++obj[arr[i]];``````

#### 第二种 indexOf

``````var cache=[],obj={};
for(var i=0;i<arr.length;i++)
cache.indexOf(arr[i])==-1?(obj[arr[i]]=1,cache.push(arr[i])):obj[arr[i]]++``````

#### 第三种 正则查找

``````var obj = {},idx=[];
for(var i=0,str = arr.join(',');i<arr.length;i++)
!obj[arr[i]]&&(patch(arr[i],str),obj[arr[i]]=1);
function patch(re,s){
re=new RegExp(re,"ig");
idx.push(s.match(re).length);
}  ``````

``````arr.reduce((prev, curr) => {
prev[curr] = prev[curr] || 0
prev[curr]++
return prev
}, {})``````

``[...new Set(arr)].map(a => ({ [a]: arr.filter(_a => _a === a).length }))``

arr.reduce((p, k) => (p[k]++ || (p[k] = 1), p), {})

``````   let countObj = {};
const arr = [1, 2, 3, 1, 5, 8, 2, 9, 9, 2, 2, 2, 3];

arr.forEach( item => {
if (countObj[item] !== undefined) {
console.log('aa')
countObj[item]++;
} else {
countObj[item] = 0;
}
})

console.log(countObj)``````

``````var arr = [1, 2, 3, 1, 5, 8, 2, 9, 9, 2, 2, 2, 3];
var tempArr = Array.from(new Set(arr)); // 去重
var countArray = tempArr.map(function(item){
var count = arr.filter(function(arrItem){return item == arrItem});
return {
value: item,
count: count.length || 0
};
});``````

``````var arr = [1, 2, 3, 1, 5, 8, 2, 9, 9, 2, 2, 2, 3];
var newArr = Array.from(new Set(arr));
var obj = [];
for(var i =0 ;i<newArr.length;i++){
obj.push("{"+newArr[i]+":"+( arr.toString().split(newArr[i]).length-1)+"}")
}
//思路：去重，然后 split 每个数字出现的次数。``````

Kenya
• 26
``````var ret = arr.reduce(function(obj,val){
if(obj[val] != undefined){
obj[val] = obj[val] + 1;
}else{
obj[val] = 1;
}
return obj;
},{});``````