Most frequent element in an array | Javascript program to find the most frequent element in an array . ; Insert all elements in hash . ; find the max frequency ; driver program
function mostFrequent ( arr , n ) { var hash = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( hash . has ( arr [ i ] ) ) hash . set ( arr [ i ] , hash . get ( arr [ i ] ) + 1 ) else hash . set ( arr [ i ] , 1 ) } var max_count = 0 , res = - 1 ; hash . forEach ( ( value , key ) => { if ( max_count < value ) { res = key ; max_count = value ; } } ) ; return res ; } var arr = [ 1 , 5 , 2 , 1 , 3 , 2 , 1 ] ; var n = arr . length ; document . write ( mostFrequent ( arr , n ) ) ;