Counting the occurrences / frequency of array elements

前端 未结 30 2103
甜味超标
甜味超标 2020-11-21 06:47

In Javascript, I\'m trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each

30条回答
  •  后悔当初
    2020-11-21 07:26

    I was solving a similar problem on codewars and devised the following solution which worked for me.

    This gives the highest count of an integer in an array and also the integer itself. I think it can be applied to string array as well.

    To properly sort Strings, remove the function(a, b){return a-b} from inside the sort() portion

    function mostFrequentItemCount(collection) {
        collection.sort(function(a, b){return a-b});
        var i=0;
        var ans=[];
        var int_ans=[];
        while(ihigh_count)
            {
                high_count=ans[i].length;
                high_ans=ans[i][0];
            }
            i++;
        }
        return high_ans;
    }
    

提交回复
热议问题