Home > Back-end >  A function in javascript to find the closest number to a certain threshold (Closest left) number in
A function in javascript to find the closest number to a certain threshold (Closest left) number in

Time:10-02

I am writing a function to find a number in an array like I have 999 the greatest number but that is not present in array so I want the only one number which is nearby 999 like 899 or 951 or 50 even if 5 is bigger than other number which is present in the array if 999 is not there how I can do that please help.

let a = [5, 5, 9, 5, 6, 888, 98, 2, 6];

a.map(function (a) {
  return a >= 900;
});

I just need one number in output

CodePudding user response:

If You Want The Closest Left Side Number :

let a = [5, 5, 9, 5, 6, 888, 98, 2, 6];
// Our Target
let target = 885;
// discard all bigger numbers
let filtered = a.filter(x=>x<=target);
// initialaze first closest
let closest = filtered[0];
for(number of filtered){
     closest = Math.abs(target-number)<=Math.abs(target-closest)?number:closest;
}
console.log(closest)

if you want to find the most closest number in array to a given number :

let a = [5, 5, 9, 5, 6, 888, 98, 2, 6];
let target = 4;
let closest = a[0];

for(number of a){
    closest = (Math.abs(target - number) <= Math.abs(target - closest))? number:closest;
}
console.log(closest)

CodePudding user response:

You can .reduce() your list updating a "running result" as you iterate over all elements in the array, and only update it if it's closer to your desired value than the previous running result:

function findClosest(list, targetValue) {
  const better = (running, element) => 
    Math.abs(targetValue - element) < Math.abs(targetValue - running);

  return list.reduce(
    (running, element) => better(running, element) ? element : running,
    list[0]
  );
}

const someList = [5, 5, 1200, 9, 5, 6, 888, 98, 2, 6];
const someValue = 900;

console.log(
  `Closest value to ${someValue}: ${findClosest(someList, someValue)}`
);

CodePudding user response:

If you want to maximum number that is less than an upper bound, then:

const target = 700;
let a = [5, 5, 9, 5, 6, 888, 98, 2, 6];

console.log(findMaxWithUpperBound(a, target));

function findMaxWithUpperBound(list: number[], upperBound: number) {
  let max = list[0];

  list.forEach((n) => {
    if (n > max && n < upperBound) {
      max = n;
    }
  });

  return max;
}
  • Related