Get the item that appears the most times in an array

后端 未结 12 1531
太阳男子
太阳男子 2020-11-27 19:18
var store = [\'1\',\'2\',\'2\',\'3\',\'4\'];

I want to find out that 2 appear the most in the array. How do I go about doing that?

12条回答
  •  萌比男神i
    2020-11-27 19:41

    Solution with emphasis to Array.prototype.forEach and the problem of getting more than one key if the max count is shared among more items.

    Edit: Proposal with one loop, only.

    var store = ['1', '2', '2', '3', '4', '5', '5'],
        distribution = {},
        max = 0,
        result = [];
    
    store.forEach(function (a) {
        distribution[a] = (distribution[a] || 0) + 1;
        if (distribution[a] > max) {
            max = distribution[a];
            result = [a];
            return;
        }
        if (distribution[a] === max) {
            result.push(a);
        }
    });
    console.log('max: ' + max);
    console.log('key/s with max count: ' + JSON.stringify(result));
    console.log(distribution);

提交回复
热议问题