It is necessary to find the element nearest to the given one in the array. The best solution I found at the moment:

var arr= [3,40,90,197], goal= 4; function myFunction() { document.getElementById("demo").innerHTML= arr.reduce(function (prev, curr) { return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev); }); } 

What is the best way to solve this problem?

  • What determines the best way? - Grundy
  • @Grundy Latest standards, efficiency, speed. Ie, for example, without if, for, etc. Desirable on CoffeeScript - CodeGust
  • This is unlikely to be something sooner than usual for . At least due to the lack of a function call for each element. In addition, the ternary operator is the same if - Grundy
  • @Grundy So, every comparison of the following elements in the for loop will be faster than .reduce ? (you need to choose the best that would please this my so-called.) - CodeGust
  • Quite possible. It all depends on the optimization of a particular browser. It is impossible to say for sure that this method is faster everywhere. There will always be some kind of browser in which there will be some kind of optimization that allows you to do something in a different way faster. - Grundy

1 answer 1

Your option (using reduce ), but on ecmascript6 . In any case, you will need to sort through the entire array, and you decide how to do it better :).

 const abs = Math.abs; const closest = (a,g) => a.reduce((p,c) => abs(cg) < abs(pg) ? c : p); closest([3, 40, 90, 197], 4); // 3 closest([1, 2, 9], -5); // 1 closest([1, 2, 9], 15); // 9 // document.getElementById("demo").innerHTML = closest([3, 40, 90, 197], 4);