Vikas Ramtel Vikas Ramtel - 6 months ago 17
Javascript Question

Getting equal or greater than number from the list of number in javascript

I have an array containing lists of numbers. I need to compare it to the variable and get the equal or slightly greater than the variable's value.

var items=[1, 2, 3.4, 3.8, 4.8, 4.2, 2.3, 1.5, 3.7];
var a=3.5;


Here, I want to compare
var a
with each item of
items
and assign
var b
with a value from
items
which is equal to or greater than th
var a
.
Note: I need only one value;in this case i need
3.7
.

Answer

Use Array#filter

var items = [1, 2, 3.4, 3.8, 4.8, 4.2, 2.3, 1.5, 3.7];
var a = 3.5;
var filtered = items.filter(function(item) {
  return item >= a;
});
console.log(filtered);

If you are expecting only one value

var items = [1, 2, 3.4, 3.8, 4.8, 4.2, 2.3, 1.5, 3.7];
var a = 3.5;
var filtered = items.filter(function(x, y) {
  return x >= a;
});
console.log(Math.min.apply(Math, filtered)); //To get the minimum value from array

console.log(filtered.sort()); //To sort the filtered values