Count of index pairs with equal elements in an array | A method to return number of pairs with equal values ; Finding frequency of each number . ; Calculating count of pairs with equal values ; Driver code
function countPairs ( arr , n ) { let hm = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( hm . has ( arr [ i ] ) ) hm . set ( arr [ i ] , hm . get ( arr [ i ] ) + 1 ) ; else hm . set ( arr [ i ] , 1 ) ; } let ans = 0 ; for ( let [ key , value ] of hm . entries ( ) ) { let count = value ; ans += ( count * ( count - 1 ) ) / 2 ; } return ans ; } let arr = [ 1 , 2 , 3 , 1 ] ; document . write ( countPairs ( arr , arr . length ) ) ;