Lahiru Nanayakkara Lahiru Nanayakkara - 18 days ago 7
Javascript Question

Find the 3 values with highest occurrences in a javascript array

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 3,4 and 5) using jQuery.

Hope that makes sense.

Thanks in advance.

Answer
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);
Comments