Find the number in an array that is closest to a given number

后端 未结 7 690
温柔的废话
温柔的废话 2021-01-03 23:07

I have an Array of integers in javascript, [5,10,15,20,25,30,35] when given a number x, how can I find the element in the array that is closest to that number?

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 23:23

    Create a temporary array of the same size as your original array, and populate it with the differences between your x and the array element.

    For example, let the temporary array be temp[], and your original array be a[]:

    temp[i]=Math.abs(x-a[i]);
    

    Then, return the index of the minimum value in temp[] to the user.

提交回复
热议问题