search

Home  >  Q&A  >  body text

javascript - How to get the number of identical elements in an array

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

怪我咯怪我咯2706 days ago793

reply all(5)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-28 09:28:34

    A simple loop will appear

    reply
    0
  • 为情所困

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

    reply
    0
  • 巴扎黑

    巴扎黑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));

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我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

    reply
    0
  • 滿天的星座

    滿天的星座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})

    reply
    0
  • Cancelreply