Count distinct elements in an array | JavaScript program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver code
function countDistinct ( arr , n ) { arr . sort ( function ( a , b ) { return a - b ; } ) ; let res = 0 ; for ( let i = 0 ; i < n ; i ++ ) { while ( i < n - 1 && arr [ i ] == arr [ i + 1 ] ) { i ++ ; } res ++ ; } return res ; } let arr = [ 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 ] ; let n = arr . length ; document . write ( countDistinct ( arr , n ) ) ;