Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting biggest number smaller than a variable in array

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)

like image 235
Emphram Stavanger Avatar asked Aug 22 '12 10:08

Emphram Stavanger


2 Answers

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.

like image 106
Donagh Hatton Avatar answered Oct 25 '22 06:10

Donagh Hatton


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);
like image 31
João Silva Avatar answered Oct 25 '22 04:10

João Silva