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?
for. At least due to the lack of a function call for each element. In addition, the ternary operator is the sameif- Grundyforloop will be faster than.reduce? (you need to choose the best that would please this my so-called.) - CodeGust