Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a number say 165

I have an array with numbers in it. Like this:

[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]

I want that the number I've got changes to the nearest, but higher number of the array.

For example I get 165 it should go tot 202

javascript arrays

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...