There is an array, for example var numArr = ["A", "C", "B", "A", "C", "D", "A", "C"]
,How to filter out the same elements and the number of the same elements
为情所困2017-06-28 09:28:34
["A", "C", "B", "A", "C", "D", "A", "C","B"].reduce((r,v)=>{
r[0].has(v)?r[1][v]?r[1][v]++:r[1][v]=2:r[0].add(v);
return r;
},[new Set,{}])[1]
// {A: 3, C: 3, B: 2}
Is this the effect? Select repeated elements (the number of occurrences is greater than or equal to 2) and count the number of occurrences of each repeated element?
巴扎黑2017-06-28 09:28:34
function checkArray(para, arr) {
let processArr = arr.filter(function(value) {
return value == para;
});
return processArr.length; // 这里返回数组长度或者相应处理
}
console.log(checkArray(1, numArr));
女神的闺蜜爱上我2017-06-28 09:28:34
You can use Map
["1", "2", 2, 0, -0, NaN, NaN, [], [], {}, {}, undefined, , , null].reduce((m, k) => {
return m.set(k, (m.get(k) || 0) + 1);
}, new Map());
Follow the following rules:
NaN = NaN
+0 = -0
"1" != 1
{} != {}
[] != []
undefined != null
Empty elements are not counted
滿天的星座2017-06-28 09:28:34
var obj={},arr=["A", "C", "B", "A", "C", "D", "A", "C","B"]
//for
for(var i=0,len=arr.length;i<len;i++){
if(obj[arr[i]]){
obj[arr[i]]++
}
else{
obj[arr[i]]=1
}
}
//forEach
arr.forEach(function(item,i){obj[arr[i]]?obj[arr[i]]++:obj[arr[i]]=1})