Javascript 按值删除数组元素的最佳方法

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

The best way to remove array element by value

javascriptarrays

提问by antonjs

I have an array like this

我有一个这样的数组

arr = ["orange","red","black","white"]

I want to augment the array object defining a deleteElem()method which acts like this:

我想增加定义一个deleteElem()方法的数组对象,它的作用如下:

arr2 = arr.deleteElem("red"); // ["orange","black","white"] (with no hole)

What is the best way to accomplish this task using just the value parameter (no index)?

仅使用值参数(无索引)完成此任务的最佳方法是什么?

回答by Maurício Linhares

Here's how it's done:

这是它的完成方式:

var arr = ["orange","red","black","white"];
var index = arr.indexOf("red");
if (index >= 0) {
  arr.splice( index, 1 );
}

This code will remove 1 occurency of "red" in your Array.

此代码将删除 Array 中出现的 1 个“红色”。

回答by Romain Vincent

I know the question already has an accepted answer but back when I was new to coding I always found splicenot straight forward at all. Even today it feels less readable.

我知道这个问题已经有了一个公认的答案,但是当我刚开始编码时,我总是发现splice根本不直接。即使在今天,它也感觉不那么可读。

But readability counts.

但可读性很重要。

So in this case I would rather use the filter method like so:

所以在这种情况下,我宁愿像这样使用过滤器方法:

arr = ["orange","red","black","white","red"]

arr = arr.filter(val => val !== "red");

console.log(arr) // ["orange","black","white"]

And that's it.

就是这样。

Note that this method removes all occurrences of "red" in your array.

请注意,此方法会删除数组中所有出现的“红色”。

Now what I find really interesting with this, is you can actually read what's happening pretty easily. Even more interesting in my case, is that you can easily go further if you work with array of objects, for example:

现在我觉得这很有趣,你实际上可以很容易地阅读正在发生的事情。就我而言,更有趣的是,如果您使用对象数组,您可以轻松地走得更远,例如:

arr = arr.filter(obj => obj.prop !== "red");

As per ryannjohnson's comment, there doesn't seem to be any caveat with this method.

根据 ryannjohnson 的评论,这种方法似乎没有任何警告。

回答by Ajeesh Joshy

There is an underscore method for this, http://underscorejs.org/#without

有一个下划线方法,http://underscorejs.org/#without

arr = ["orange","red","black","white"];

arr = _.without(arr, "red");

回答by Mauricio Wolff

Or simply check all items, create a new array with non equal and return it.

或者简单地检查所有项目,创建一个不相等的新数组并返回它。

var arr = ['orange', 'red', 'black', 'white'];

console.info('before: ' + JSON.stringify(arr));

var deleteElem = function ( val ) {
    var new_arr = [];
    for ( var i = 0; i < this.length; i++ ) {
        if ( this[i] !== val ) {
            new_arr.push(this[i]);
        }
    }
    return new_arr;
};

arr = deleteElem('red');

console.info('after: ' + JSON.stringify(arr));

http://jsfiddle.net/jthavn3m/

http://jsfiddle.net/jthavn3m/

回答by chaoticflow

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

诀窍是从头到尾遍历数组,这样在删除元素时就不会弄乱索引。

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]

arr 现在是 ["red", "black", "white"]

回答by Jiri Kriz

Array.prototype.deleteElem = function(val) {
    var index = this.indexOf(val); 
    if (index >= 0) this.splice(index, 1);
    return this;
}; 
var arr = ["orange","red","black","white"];
var arr2 = arr.deleteElem("red");

回答by Horst Walter

My approach, let's see what others have to say. It supports an "equals" method as well.

我的做法,看看别人怎么说。它也支持“equals”方法。

 // Remove array value
 // @param {Object} val
 Array.prototype.removeByValue = function (val) {
    for (var i = 0; i < this.length; i++) {
       var c = this[i];
       if (c == val || (val.equals && val.equals(c))) {
          this.splice(i, 1);
          break;
       }
    }
 };

Read https://stackoverflow.com/a/3010848/356726for the impact on iterations when using prototype with Array.

阅读https://stackoverflow.com/a/3010848/356726了解将原型与 Array 一起使用时对迭代的影响。

回答by Terry Lin

The best way is to use splice and rebuild new array, because after splice, the length of array does't change.

最好的方法是使用拼接并重建新数组,因为拼接后,数组的长度不会改变。

Check out my answer:

看看我的回答:

function remove_array_value(array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array.splice(index, 1);
        reindex_array(array);
    }
}
function reindex_array(array) {
   var result = [];
    for (var key in array) {
        result.push(array[key]);
    }
    return result;
}

example:

例子:

var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
remove_array_value(example_arr, 'banana');

banana is deleted and array length = 2

香蕉被删除,数组长度 = 2

回答by Claudio Djohnnatha

If order the array (changing positions) won't be a problem you can solve like:

如果订购数组(更改位置)不会成为问题,您可以解决如下问题:

var arr = ["orange","red","black","white"];
arr.remove = function ( item ) {
  delete arr[item];
  arr.sort();
  arr.pop();
  console.log(arr);
}

arr.remove('red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by ?ime Vidas

Here you go:

干得好:

arr.deleteElem = function ( val ) {
    for ( var i = 0; i < this.length; i++ ) {
        if ( this[i] === val ) {
            this.splice( i, 1 );
            return i;
        }
    }
};

Live demo:http://jsfiddle.net/4vaE2/3/

现场演示:http : //jsfiddle.net/4vaE2/3/

The deleteElemmethod returns the index of the removed element.

deleteElem方法返回已删除元素的索引。

var idx = arr.deleteElem( 'red' ); // idx is 1