简体   繁体   中英

Getting the closest value

I've come across this problem a few times now and I don't have a nice solution for it.

Suppose I have a simple array of numbers at non-fixed intervals, myArray . I would like to have a function that can take a whole number (it could be negative) and return the value in the array that it is closest to. In my example, I'd like it to return 850 .

I think I need to use the upper and lower variables to work out which of the array values is closest to the value I pass in.

Am I on the right track or is there a more efficient way of achieving this and could anyone give me a nudge in the right direction?

Here is what I have so far:

var myArray = [0,850,1800,2500,3300];

function snapTo(value){
    var upper = -1;
    var lower = -1;

    // if the value is bigger than the last array value
    if(value > myArray[myArray.length-1]){
        upper = myArray[myArray.length-1];
        lower = myArray[myArray.length-2];
    // if the value is smaller than the first array value
    } else if(value < myArray[0]){
        upper = myArray[1];
        lower = myArray[0];
    } else {
        for(var i = 0, i < myArray.length, i++){
            if(value > myArray[i]){
                upper = myArray[i];
                lower = myArray[i-1];
                break;
            }
        }
    }

    // x being the index of the closest array value to the one passed in
    return myArray[x];
}

snapTo(1200);

您的先生正在寻找二进制搜索而不是!

I would give you the nudge that you don't specifically need to check whether the value is larger or smaller than the previous array value. Instead just work out the absolute difference between your target value and the "current" array element. And compare it to the best difference so far to decide whether this array index is the winning candidate so far...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM