Home > Software design >  get the number with the smallest value closest to the goal in the array
get the number with the smallest value closest to the goal in the array

Time:10-03

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.

CodePudding user response:

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);

CodePudding user response:

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

const distance = counts.map((num) => Math.abs(num-goal));
const smallestDistance = Math.min(...distance);
const closestValueIndex = distance.indexOf(smallestDistance)
console.log(counts[closestValueIndex]);  // 4

CodePudding user response:

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 < goal ? curr : prev);
});

console.log(closest);

CodePudding user response:

If I'm understanding your goal correctly, you want to sort the array high to low, then loop through and return the first number less than or equal the goal.

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

counts.sort((a, b) => b - a)

for(let i=0; i< counts.length; i  ) {
  if(counts[i] - goal <= 0) {
    closest = counts[i]
    break
  }
}

console.log(closest)

  • Related