Reputation: 115
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
.
Upvotes: 1
Views: 2695
Reputation: 386730
A single loop with a Array#reduce
should help.
var items = [1, 2, 3.4, 3.8, 4.8, 4.2, 2.3, 1.5, 3.7],
a = 3.5,
result = items.reduce(function (r, b) {
return b > a && (r === undefined || b < r) ? b : r;
}, undefined);
console.log(result);
Upvotes: 0
Reputation: 115242
Use filter()
method to filter value from array and get minimum value from array using Math.min
with apply()
var items = [1, 2, 3.4, 3.8, 4.8, 4.2, 2.3, 1.5, 3.7];
var a = 3.5;
console.log(
// get min value from filtered array
Math.min.apply(Math, items.filter(function(v) {
return v >= a; // filter value greater than or equal
}))
)
Or use reduce()
method
var items = [1, 2, 3.4, 3.8, 4.8, 4.2, 2.3, 1.5, 3.7];
var a = 3.5;
console.log(
items.reduce(function(r, v) {
// check value is greater than or equal and then return the min value
return (v >= a && (r == undefined || v < r)) ? v : r;
}, undefined)
)
Upvotes: 4
Reputation: 36609
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
Upvotes: 4