javascript - How to get the number of identical elements in an array
怪我咯
怪我咯 2017-06-28 09:26:34
0
5
825

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(5)
伊谢尔伦

A simple loop will appear

为情所困
["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?

巴扎黑
function checkArray(para, arr) {
    let processArr = arr.filter(function(value) {
        return value == para;
    });

    return processArr.length;  // 这里返回数组长度或者相应处理
}

console.log(checkArray(1, numArr));
女神的闺蜜爱上我

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

滿天的星座
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})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template