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

后端 未结 7 730
温柔的废话
温柔的废话 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 23:28

    Since Array.reduce is a reality for so long (even IE9 supports it), the problem is easily solvable with it. This way, no need to sort the array first (no array mutation at all):

    var numbers = [20, 25, 30, 35, 5, 10, 15], x = 7;
    
    var output = numbers.reduce(function (prev, curr) {
      return Math.abs(curr - x) < Math.abs(prev - x) ? curr : prev
    });
    
    console.log(output);

    You can go further and solve it with only one line of ES6 (ECMAScript 2015) syntax, by using an arrow function (but with no IE support in this case):

    const numbers = [20, 25, 30, 35, 5, 10, 15], x = 7;
    
    const output = numbers.reduce((prev, curr) => Math.abs(curr - x) < Math.abs(prev - x) ? curr : prev);
    
    console.log(output);

    Of course, for flexibility and reusability, it's easy to make it as a function:

    const closest = (array, goal) => array.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
    
    console.log(closest([20, 25, 30, 35, 5, 10, 15], 7));
    console.log(closest([20, 25, 30, 35, 5, 10, 15], 8));
    console.log(closest([1, 5, 7], -5));
    console.log(closest([1, 5, 7], 4));
    console.log(closest([1, 5, 7], 20));

提交回复
热议问题