Difference between sum of odd and even frequent elements in an Array | Function to find the sum of all even and odd frequent elements in an array ; Stores the frequency of array elements ; Traverse the array ; Update frequency of current element ; Stores sum of odd and even frequent elements ; Traverse the map ; If frequency is odd ; Add sum of all occurrences of current element to sum_odd ; If frequency is even ; Add sum of all occurrences of current element to sum_even ; Calculate difference between their sum ; Return diff ; Driver Code
function findSum ( arr , N ) { var mp = { } ; for ( let i = 0 ; i < N ; i ++ ) mp [ arr [ i ] ] = 0 ; for ( let i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } var sum_odd = 0 , sum_even = 0 ; for ( let itr in mp ) { if ( mp [ itr ] % 2 != 0 ) { sum_odd += ( itr ) * ( mp [ itr ] ) ; } if ( mp [ itr ] % 2 == 0 ) { sum_even += ( itr ) * ( mp [ itr ] ) ; } } var diff = sum_even - sum_odd ; return diff ; } var arr = new Array ( 1 , 5 , 5 , 2 , 4 , 3 , 3 ) ; var N = arr . length ; console . log ( findSum ( arr , N ) ) ;