如何使用小于和大于 javascript 的条件删除数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25620836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:45:30  来源:igfitidea点击:

How to remove array values using condition less than and greater than in javascript

javascript

提问by divakar

I want to remove values from using less than and greater than condition for example my array is

我想从使用小于和大于条件中删除值,例如我的数组是

138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120

so now my minimum value is 120 and maximum value is 130. I want to remove all the remaining elements from the array. Is this possible in javascript.

所以现在我的最小值是 120,最大值是 130。我想从数组中删除所有剩余的元素。这在javascript中可能吗?

I am newbie so any help would be appreciated.

我是新手,所以任何帮助将不胜感激。

回答by adeneo

Sure, just filter the array

当然,只需过滤数组

var arr = [
    138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120
]

var new_arr = arr.filter(function(x) {
    return x > 120 && x < 130;
});

FIDDLE

小提琴

Use >=and <=to include 120 and 130 as well etc.

使用>=<=也包括 120 和 130 等。

回答by A.T.

using mapas below,

使用地图如下,

$.map(a,function(o,i){  if(o < 130 && o > 120) return o; })

回答by Mr. Polywhirl

Just going to extend on the filter and throw it into a reusable function:

只是要扩展过滤器并将其放入可重用的函数中:

var arr = [
    138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120
]
/*
 * @param arr Array of integers
 * @param min Minimum (Inclusive)
 * @param max Maximum (Exclusive)
 */
var filterInRange = function(arr, min, max) {
    return arr.filter(function(item) {
        return item >= min && item < max;
    });
}

console.log(filterInRange(arr, 120, 131).sort()); // [120,124,126,128,128,130]

回答by Alireza

Simply use filter, it's created for things like this, the code below should do the job as you want:

简单地使用过滤器,它是为这样的事情创建的,下面的代码应该按照你的意愿完成工作:

//ES6
var arr = [138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120];
var filteredArr = arr.filter(n => n>120 && n<130); //[124, 128, 126, 128]

回答by ben rudgers

Use the array.prototype.filter()method to return a new array containing only those elements passing a Boolean test.

使用该array.prototype.filter()方法返回一个新数组,该数组仅包含通过布尔测试的那些元素。

  function isBigEnough(element) { 
    return element >= 10; } 


  var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);

Returns a new array [12, 130, 44].

返回一个新数组[12, 130, 44]

Along with array.prototype.map()and array.prototype.reduce()array.prototype.filter()facilitates using a functional programming style in JavaScript.

array.prototype.map()并促进在 JavaScript 中使用函数式编程风格。array.prototype.reduce()array.prototype.filter()