JS : Biggest element of an array, less than a given variable

JS : Biggest element of an array, less than a given variable

Given :
var array = [1,2,5,10];
var limit = 8;

I am looking for a way to find the biggest element of the array, less than the limit 8. something like :
Math.max(array, "while < limit");

I tried :
Math.min(Math.max(array), limit)

which does not work in all cases for array and limit, obviously.
EDIT :
The input array is not necessarily sorted :
var array = [10,-10,10,-10];
var limit = 5;

Expected result is -10.

Solutions/Answers:

Answer 1:

var array = [1,2,5,10];
var limit = 8;
alert(Math.max.apply(Math, array.filter(function(x){return x <= limit})));

Answer 2:

You can sort, filter and then pop

var array = [1,2,5,10];
var limit = 8;

var largest = array.sort().filter(item => (item < limit)).pop();

console.log(largest);

Answer 3:

You can either just do a simple for loop, you can filter all numbers less than the max and sort and max, or you can use reduce which is just like doing a for loop.

for loop (could use forEach)

var array = [1, 2, 5, 10];
var limit = 8;
var result = array[1];
for (var i = 1; i < array.length; i++) {
  if (array[i] <= limit && array[i] > result) {
    result = array[i];
  }
}
console.log(result);

Filter with Max

var array = [1, 2, 5, 10];
var limit = 8;

var result = Math.max.apply([], array.filter(function(val) {
  return val < limit
}));
console.log(result);

Reduce

var array = [1,2,5,10];
var limit = 8;

var temp = array[0];
var result = array.reduce( function (num, val ) {
    return val > num && val <= limit ? val : num
}, temp);
console.log(result)

Answer 4:

You can try in this way:

var array = [1,2,5,10,7];
var limit = 8;

var max=0;
for(var i=0;i<array.length;i++)
{   
   if(array[i] > max && array[i] < limit)
      max=array[i];
}

console.log(max);

Answer 5:

var array = [1,2,5,10];
var limit = 8;
var closest = null;

array.forEach(function(el){
  if (el <= limit && (closest == null || (limit - el) < (limit - closest))) {
    closest = el;
  }
});

alert(closest);

References

Loading...