0

I have javascript array in which I need to return 3 values with highest occurrences. Lets say we have an array like this.

[1,3,4,5,2,3,4,5,6,7,8,5,4,5,3,5,6,7,3,5,6,5,6,3,4,5,6,6]

1 - 1 time 2 - 1 time 3 - 5 times 4 - 4 times 5 - 8 times 6 - 6 times 7 - 2 times 8 - 1 time

How can we return 3 values with most occurrences (in this case 4, 5 and 6) using jQuery.

Hope that makes sense.

Thanks in advance.

LSN
  • 328
  • 2
  • 14
  • there is no such thing as a jQuery array, it's a javascript array – Jaromanda X Nov 18 '16 at 01:47
  • You could check [this question](http://stackoverflow.com/questions/5658547/is-there-any-way-to-count-the-number-of-occurences-in-a-jquery-array) – Fredrik Lundvall Nov 18 '16 at 01:51
  • 2
    Possible duplicate of [Counting the occurrences of JavaScript array elements](http://stackoverflow.com/questions/5667888/counting-the-occurrences-of-javascript-array-elements) – Dez Nov 18 '16 at 01:59

2 Answers2

0
var arr = [1,3,4,5,2,3,4,5,6,7,8,5,4,5,3,5,6,7,3,5,6,5,6,3,4,5,6,6];

var x = arr.reduce(function(result, item) {
    result[item] = result[item] || {count:0};
    ++result[item].count;
    return result;
}, {});
var y = Object.keys(x).sort(function(a, b) {
    return x[b].count - x[a].count;
}).slice(0,3);
console.log(y);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4,1,1,2,1,1,1,3,3,3,3,3];
var counts = {};

for(var i = 0; i< arr.length; i++) {
    var num = arr[i];
    counts[num] = counts[num] ? counts[num]+1 : 1;
}
console.log(counts);// return object which return key value pair count like  Object {2: 5, 4: 1, 5: 3, 9: 1} 2 five time,4 one time, 5 three time in array
var keysSorted = Object.keys(counts).sort(function(a,b){return counts[a]-counts[b]})
alert(keysSorted); 

alert(keysSorted); //this is asc order, last 3 values are max occurance
Karan Singh
  • 876
  • 1
  • 6
  • 12