How to count duplicate value in an array in javascript

前端 未结 28 1404
后悔当初
后悔当初 2020-11-22 06:07

Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount =          


        
相关标签:
28条回答
  • 2020-11-22 06:37

    // new example.
    var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];
    
    function findOdd(para) {
      var count = {};
      para.forEach(function(para) {
      count[para] = (count[para] || 0) + 1;
      });
      return count;
    }
    
    console.log(findOdd(str));

    0 讨论(0)
  • 2020-11-22 06:38

    Duplicates in an array containing alphabets:

    var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],
      sortedArr = [],
      count = 1;
    
    sortedArr = arr.sort();
    
    for (var i = 0; i < sortedArr.length; i = i + count) {
      count = 1;
      for (var j = i + 1; j < sortedArr.length; j++) {
        if (sortedArr[i] === sortedArr[j])
          count++;
      }
      document.write(sortedArr[i] + " = " + count + "<br>");
    }

    Duplicates in an array containing numbers:

    var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
      sortedArr = [],
      count = 1;
    sortedArr = arr.sort(function(a, b) {
      return a - b
    });
    for (var i = 0; i < sortedArr.length; i = i + count) {
      count = 1;
      for (var j = i + 1; j < sortedArr.length; j++) {
        if (sortedArr[i] === sortedArr[j])
          count++;
      }
      document.write(sortedArr[i] + " = " + count + "<br>");
    }

    0 讨论(0)
  • 2020-11-22 06:39

    Simple is better, one variable, one function :)

    const counts = arr.reduce((acc, value) => ({
       ...acc,
       [value]: (acc[value] || 0) + 1
    }), {});
    
    0 讨论(0)
  • 2020-11-22 06:40

    function count() {
        array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
    
        array_elements.sort();
    
        var current = null;
        var cnt = 0;
        for (var i = 0; i < array_elements.length; i++) {
            if (array_elements[i] != current) {
                if (cnt > 0) {
                    document.write(current + ' comes --> ' + cnt + ' times<br>');
                }
                current = array_elements[i];
                cnt = 1;
            } else {
                cnt++;
            }
        }
        if (cnt > 0) {
            document.write(current + ' comes --> ' + cnt + ' times');
        }
    
    }
    
    count();

    Demo Fiddle

    You can use higher-order functions too to do the operation. See this answer

    0 讨论(0)
提交回复
热议问题