Alex Rivera | Logout

Selecting biggest number smaller than a variable in array

Asked 2012-08-22T10:04:37.500
12

I have a JavaScript array and a variable like so;

var a = [0, 1200, 3260, 9430, 13220],
    b = 4500;

What would be the smartest way to select the largest value in the array that's still smaller than or equal to the variable?

In this example, I'd need to select 3260.

I could do something like this;

$.each(a, function(i){
    if(a[i] <= b && a[i+1] > b){
        var c = a[i];
        return false;
    }
});

But I'm thinking that might not work if the selected array value is the last one. Not to mention, to me it looks like a lot of code for something rather simple.

Is there a smarter/less verbose way of achieving what I'm after?

(and yes, I know I shouldn't have used a jQuery loop for that but I'm lazy when typing examples)

Edit
Report

1 Answer

3

Is the a array always sorted? In this case, you could optimize your code along those lines (you might want to check the indexes, I haven't checked the code):

var beginning = 0;
var end = a.length;
while ((end-beginning)>1) {
    var currentIndex = Math.floor((beginning+end)/2);;
    if (a[currentIndex] < b) {
        beginning = currentIndex;
    } else if (a[currentIndex] > b){
        end = currentIndex;
    } else {
        beginning=end=currentIndex;
    }
}
var max = a[beginning];
answered 2012-08-22T10:19:42.990

Your Answer