Replace each element of Array with it 's corresponding rank | Function to assign rank to array elements ; Copy input array into newArray ; Sort newArray [ ] in ascending order ; Map to store the rank of the array element ; Update rank of element ; Assign ranks to elements ; Given array arr [ ] ; Function call ; Print the array elements
function changeArr ( input , N ) { var newArray = JSON . parse ( JSON . stringify ( input ) ) ; newArray . sort ( ( a , b ) => a - b ) ; var i ; var ranks = new Map ( ) ; var rank = 1 ; for ( var index = 0 ; index < N ; index ++ ) { var element = newArray [ index ] ; if ( ! ranks . has ( element ) ) { ranks . set ( element , rank ) ; rank ++ ; } } for ( var index = 0 ; index < N ; index ++ ) { var element = input [ index ] ; input [ index ] = ranks . get ( input [ index ] ) ; } return input ; } var arr = [ 100 , 2 , 70 , 2 ] ; var N = arr . length ; arr = changeArr ( arr , N ) ; document . write ( " " ) ; for ( var i = 0 ; i < N - 1 ; i ++ ) { document . write ( arr [ i ] + " " ) ; } document . write ( arr [ N - 1 ] + " " ) ;