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

后端 未结 7 2207
抹茶落季
抹茶落季 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条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 20:18

    I really do not think there is a need for 2 loops in this solution. You can look at this prototyping code which uses a simple data structure called map:

    var arr=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
    var map = {};
    var mostFrequentElement = arr[0];
    function findMostFrequent(){
        for(var i = 0; imap[mostFrequentElement]){
                    mostFrequentElement = arr[i];
                }
            }
        }
        alert(mostFrequentElement);
    }
    

提交回复
热议问题