Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get the number with the smallest value closest to the goal in the array

I need Obtain the nearest smallest number of an array, not the closest number

var counts = [4, 9, 15, 6, 2],
  goal = 13;

var closest = counts.reduce(function(prev, curr) {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});

console.log(closest);

Above, the result is 15 but it should be 9 as I want the lowest number closest to the goal number.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can filter your array so that you get an array with numbers that are smaller than your goal number. Once you have this array, the largest number in that array will naturally be the closest number to goal, which you can obtain by spreading your array into Math.max():

const counts = [4, 9, 15, 6, 2],
  goal = 13;

const closest = Math.max(...counts.filter(num => num < goal));

console.log(closest);

One thing to note, the above will struggle with large arrays (mainly due to the fact that Math.max() has an argument limit), a more optimised option would be to use a regular loop, for example:

const counts = [4, 9, 15, 6, 2], goal = 13;
let closest = -Infinity;
for(const num of counts)
  if(num < goal && num > closest) closest = num;

console.log(closest);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading