Find number from given list for which value of the function is closest to A | Function to find number from given list for which value of the function is closest to A ; Stores the final index ; Declaring a variable to store the minimum absolute difference ; Finding F ( n ) ; Updating the index of the answer if new absolute difference is less than tmp ; Driver code
function leastValue ( P , A , N , a ) { let ans = - 1 ; let tmp = Number . MAX_VALUE ; for ( let i = 0 ; i < N ; i ++ ) { let t = ( P - a [ i ] * 0.006 ) ; if ( Math . abs ( t - A ) < tmp ) { tmp = Math . abs ( t - A ) ; ans = i ; } } return a [ ans ] ; } let N = 2 , P = 12 , A = 2005 ; let a = [ 1000 , 2000 ] ; document . write ( leastValue ( P , A , N , a ) )