Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Get closest (but higher) number in an array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...