Count distinct elements in an array | JavaScript program to count distinct elements in a given array ; Pick all elements one by one ; If not printed earlier , then print it ; Driver program to test above function
function countDistinct ( arr , n ) { let res = 1 ; for ( let i = 1 ; i < n ; i ++ ) { let j = 0 ; for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] === arr [ j ] ) break ; if ( i === j ) res ++ ; } return res ; } let arr = [ 12 , 10 , 9 , 45 , 2 , 10 , 10 , 45 ] ; let n = arr . length ; document . write ( countDistinct ( arr , n ) ) ;