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

后端 未结 7 735
温柔的废话
温柔的废话 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:24

    Probably the easiest thing to do is sort based on distance from the reference value x, and then take the first item.

    The built-in Array.prototype.sort() can take a comparison function which will be called for pairs of values from the array. Then the key is simply to pass in a comparison function which compares the two values based on their distance from the reference value x.

    let x = 8;
    let array = [5, 10, 15, 20, 25, 30, 35];
    let closest = array.sort( (a, b) => Math.abs(x - a) - Math.abs(x - b) )[0];
    

    See this simple demo.

提交回复
热议问题