Selecting biggest number smaller than a variable in array
Another way you could to it is through a combination of array filtering and apply(), which I think is a very readable approach. The call to filter() just returns an array of elements in a which don't satisfy the predicate function and then apply() calls Math.max with each element as an argument.
var a = [1, 2, 3, 4, 5];
var b = 4;
var result = Math.max.apply(Math, a.filter(function(x){return x <= b}));
Result will be equal to 4.
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];
var max = Number.MIN_VALUE;
for (var i = 0; i < a.length; i++) {
if (a[i] <= b && a[i] > max) {
max = a[i];
}
}
I think the above approach is quite simple, readable, and not very verbose. An alternative would be to use reduce
, like so:
var max = a.reduce(function (i, j) { return j <= b ? Math.max(i, j) : i }, Number.MIN_VALUE);
grep() of jQuery
var a = [0, 1200, 3260, 9430, 13220],
b = 4500;
var c= Math.max.apply( Math,$.grep(a,function(n){return n<=b}));
document.write(c)
WORKING DEMO