0

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);
boz
  • 4,891
  • 5
  • 41
  • 68
  • 1
    http://stackoverflow.com/questions/3561275/using-jquery-how-would-i-find-the-closest-match-in-an-array-to-a-specified-num – jwaliszko Oct 23 '12 at 11:41

2 Answers2

3

You sir are looking for a binary search instead of that for!

alexandernst
  • 14,352
  • 22
  • 97
  • 197
1

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...

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • Thanks for this but I decided to go down the binary search route - no point re-inventing the wheel. – boz Oct 23 '12 at 13:47
  • @boz Sure - that is likely to be the best approach to the problem. I merely wanted to point out how your current approach could be improved, for learning's sake. – Andrzej Doyle Oct 23 '12 at 14:30