[Solved] Get closest (but higher) number in an array


Here’s a method using Array.forEach():

const number = 165;
const candidates = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];

//looking for the lowest valid candidate, so start at infinity and work down
let bestCandidate = Infinity;

//only consider numbers higher than the target
const higherCandidates = candidates.filter(candidate => candidate > number);

//loop through those numbers and check whether any of them are better than
//our best candidate so far
higherCandidates.forEach(candidate => {
    if (candidate < bestCandidate) bestCandidate = candidate;
});

console.log(bestCandidate); //the answer, or Infinity if no valid answers exist

3

solved Get closest (but higher) number in an array