javascript - 根据条件删除数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15995963/
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-27 02:52:33  来源:igfitidea点击:

javascript - remove array element on condition

javascript

提问by dk123

I was wondering how I'd go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery)

我想知道如何在 javascript 中实现一种方法,该方法删除清除某个条件的数组的所有元素。(最好不使用 jQuery)

Ex.

前任。

ar = [ 1, 2, 3, 4 ];
ar.removeIf( function(item, idx) {
    return item > 3;
});

The above would go through each item in the array and remove all those that return truefor the condition (in the example, item > 3).

上面的代码将遍历数组中的每个项目并删除所有return true满足条件的项目(在示例中,项目 > 3)。

I'm just starting out in javascript and was wondering if anyone knew of a short efficient way to get this done.

我刚开始使用 javascript,想知道是否有人知道一种简短有效的方法来完成这项工作。

--update--

——更新——

It would also be great if the condition could work on object properties as well.

如果条件也适用于对象属性,那就太好了。

Ex.

前任。

ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
    return item.str == "c";
});

Where the item would be removed if item.str == "c"

如果该项目将被删除 item.str == "c"

--update2--

--更新 2--

It would be nice if index conditions could work as well.

如果索引条件也能正常工作,那就太好了。

Ex.

前任。

ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
    return idx == 2;
});

采纳答案by pickypg

You could add your own method to Arraythat does something similar, if filterdoes not work for you.

如果对您Array不起作用,您可以添加自己的方法来做类似的事情filter

Array.prototype.removeIf = function(callback) {
    var i = 0;
    while (i < this.length) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
        else {
            ++i;
        }
    }
};

To me, that's one of the coolest features of JavaScript. Ian pointed out a more efficient way to do the same thing. Considering that it's JavaScript, every bit helps:

对我来说,这是 JavaScript 最酷的特性之一。伊恩指出了一种更有效的方法来做同样的事情。考虑到它是 JavaScript,每一点都有帮助:

Array.prototype.removeIf = function(callback) {
    var i = this.length;
    while (i--) {
        if (callback(this[i], i)) {
            this.splice(i, 1);
        }
    }
};

This avoids the need to even worry about the updating lengthor catching the next item, as you work your way left rather than right.

这避免了甚至担心更新length或捕获下一个项目的需要,因为您向左而不是向右工作。

回答by Klaster_1

You can use Array filter method.

您可以使用数组过滤器方法

The code would look like this:

代码如下所示:

ar = [1, 2, 3, 4];
ar = ar.filter(item => !(item > 3));
console.log(ar) // [1, 2, 3]

回答by Blender

You can use Array.filter(), which does the opposite:

您可以使用Array.filter(),它的作用相反:

ar.filter(function(item, idx) {
    return item <= 3;
});

回答by Satoshi Suzuki

You can use lodash.remove

您可以使用lodash.remove

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});

console.log(array);
// => [1, 3]

console.log(evens);
// => [2, 4]

回答by michal.jakubeczy

Make it a one-liner with arrow function:

使其成为具有箭头功能的单线:

ar = ar.filter(i => i > 3);

回答by PSL

I love these kinds of questions and just a different version from me too... :)

我喜欢这些类型的问题,而且与我的版本不同...... :)

Array.prototype.removeIf = function(expression) {
   var res = [];
    for(var idx=0; idx<this.length; idx++)
    {
      var currentItem = this[idx];
        if(!expression(currentItem))
        {
            res.push(currentItem);
        }
    }
    return res;
}

ar = [ 1, 2, 3, 4 ];
var result = ar.removeIf(expCallBack);


console.log(result);
function expCallBack(item)
{
    return item > 3;
}

回答by vamsikrishnamannem

simply write the following example if condition could work on object properties as well

如果条件也适用于对象属性,只需编写以下示例

var ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
var newArray = [];
for (var i = 0, len = ar.length; i<len; i++) {
        if (ar[i].str == "b") 
        {newArray.push(ar[i]);};
 };
console.log(newArray);

See the example Live Example

查看示例现场示例