Find the most frequent item of an array (not just strings)

后端 未结 7 2203
抹茶落季
抹茶落季 2020-12-10 19:42

Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.

7条回答
  •  旧时难觅i
    2020-12-10 20:38

    Using Array.prototype.reduce() and a temporary variable, You could do it this way (4 lines):

    var arr2 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
    var newArr = arr2.slice().sort(), most = [undefined, 0], counter = 0;
    
    newArr.reduce(function(old, chr){
       old == chr ? ++counter > most[1] && (most = [chr, counter]) : (counter = 1)
       return chr
    });
    
    alert(most[0] + " ( "+most[1]+" times )");

    Explanation Excuse my english.

    Using Array.prototype.reduce() can simplify your work. The following function first sorts their characters as 22333349aaaaa, then this counts your characters in sequence. I created a temp variable most to store the data of the character most repeated.

    Note This only works for items of single digits.

提交回复
热议问题