Store the difference between the prime and the array element
let minm = Math . abs ( primes [ x ] - arr [ i ] ) ; if ( x > 1 ) { minm = Math . min ( minm , Math . abs ( primes [ x - 1 ] - arr [ i ] ) ) ; } ans += minm ; } return ans ; }