Extracting the most duplicate value from an array in JavaScript (with jQuery)

前端 未结 5 1226
不思量自难忘°
不思量自难忘° 2020-12-01 17:26

I have several array to deal with. I need to extract the most duplicate value from each array.

From [3, 7, 7, 7], I need to find the value 7

5条回答
  •  爱一瞬间的悲伤
    2020-12-01 18:18

    Here's a simpler and faster version using only JavaScript:

    var arr = [3, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];
    var counts = {}, max = 0, res;
    for (var v in arr) {
      counts[arr[v]] = (counts[arr[v]] || 0) + 1;
      if (counts[arr[v]] > max) { 
        max = counts[arr[v]];
        res = arr[v];
      }
    }
    alert(res + " occurs " + counts[res] + " times");
    

    Note that this is a much more efficient since you're looping over the data once, if you're sorting very large arrays this will start to matter.

提交回复
热议问题