angularjs - Getting equal or greater than number from the list of number in javascript - Stack Overflow

I have an array containing lists of numbers. I need to pare it to the variable and get the equal or sli

I have an array containing lists of numbers. I need to pare 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 pare 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.

I have an array containing lists of numbers. I need to pare 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 pare 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.

Share Improve this question edited May 29, 2016 at 8:26 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked May 29, 2016 at 8:13 Bikash RamtelBikash Ramtel 1151 gold badge3 silver badges13 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

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

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)
)

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745210589a4616813.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信