简体   繁体   English

javascript - 在条件下删除数组元素

[英]javascript - remove array element on condition

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.我想知道如何在 javascript 中实现一个方法,该方法删除清除某个条件的数组的所有元素。 (Preferably without using jQuery) (最好不使用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 true for the condition (in the example, item > 3).以上将 go 遍历数组中的每个项目,并删除所有为条件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.如果条件也适用于 object 属性,那就太好了。

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

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]

You could add your own method to Array that does something similar, if filter does not work for you.如果filter对您不起作用,您可以将自己的方法添加到Array ,以执行类似的操作。

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.对我来说,这是 JavaScript 最酷的特性之一。 Ian pointed out a more efficient way to do the same thing.伊恩指出了一种更有效的方法来做同样的事情。 Considering that it's JavaScript, every bit helps:考虑到它是 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 length or catching the next item, as you work your way left rather than right.这避免了甚至需要担心更新length或捕捉下一个项目,因为您向左而不是向右工作。

You can use Array.filter() , which does the opposite:您可以使用Array.filter() ,它的作用相反:

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

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]

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

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

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

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查看示例现场示例

if you need to remove exactly one item, and you know for sure that the item exists, you can use this one-liner:如果您需要完全删除一项,并且您确定该项目存在,则可以使用此单行:

ar.splice(ar.findIndex(el => el.id === ID_TO_REMOVE), 1);

// or with custom method:
let ar = [ {id:1, str:"a"}, {id:2, str:"b"}, {id:3, str:"c"}, {id:4,str:"d"} ];
ar.removeById = id => ar.splice(ar.findIndex(el => el.id === id), 1);
ar.removeById(ID_TO_REMOVE);

http://jsfiddle.net/oriadam/72kgprw5/ http://jsfiddle.net/oriadam/72kgprw5/

ES6 only仅限 ES6

我对对象数组的解决方案是:

ar.filter((item, index) => index <=3

For the in-place remove, my solution is对于就地删除,我的解决方案是

ar.filter(item => !(item > 3))
  .forEach(obsoleteItem => ar.splice(ar.indexOf(obsoleteItem), 1));

Incorrect way不正确的方式

First of all, any answer that suggests to use filter does not actually remove the item.首先,任何建议使用filter的答案实际上都不会删除该项目。 Here is a quick test:这是一个快速测试:

var numbers = [1, 2, 2, 3];
numbers.filter(x => x === 2);
console.log(numbers.length);

In the above, the numbers array will stay intact (nothing will be removed).在上面, numbers数组将保持不变(不会删除任何内容)。 The filter method returns a new array with all the elements that satisfy the condition x === 2 but the original array is left intact. filter方法返回一个新数组,其中包含满足条件x === 2的所有元素,但原始数组保持不变。

Sure you can do this:当然你可以这样做:

var numbers = [1, 2, 2, 3];
numbers = numbers.filter(x => x === 2);
console.log(numbers.length);

But that is simply assigning a new array to numbers .但这只是将一个新数组分配给numbers


Correct way to remove items from array从数组中删除项目的正确方法

One of the correct ways, there are more than 1, is to do it as following.正确的方法之一,不止1,是按照以下方式进行。 Please keep in mind, the example here intentionally has duplicated items so the removal of duplicates can be taken into consideration.请记住,此处的示例故意包含重复项,因此可以考虑删除重复项。

var numbers = [1, 2, 2, 3];

// Find all items you wish to remove
// If array has objects, then change condition to x.someProperty === someValue
var numbersToRemove = numbers.filter(x => x === 2);

// Now remove them
numbersToRemove.forEach(x => numbers.splice(numbers.findIndex(n => n === x), 1));

// Now check (this is obviously just to test)
console.log(numbers.length);
console.log(numbers);

Now you will notice length returns 2 indicating only numbers 1 and 3 are remaining in the array.现在您会注意到length返回 2,表示数组中只剩下数字 1 和 3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM