Least frequent element in an array | JavaScript program to find the least frequent element in an array . ; Insert all elements in hash . ; find the min frequency ; driver program
function leastFrequent ( 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 min_count = n + 1 , res = - 1 ; hash . forEach ( ( value , key ) => { if ( min_count >= value ) { res = key ; min_count = value ; } } ) ; return res ; } var arr = [ 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 ] ; var n = arr . length ; document . write ( leastFrequent ( arr , n ) ) ;