The best way to remove array element by value

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:

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


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.


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

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.


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

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

arr = _.without(arr, "red");
链接地址: http://www.djcxy.com/p/19040.html

上一篇: 根据每个元素的长度对数组进行排序

下一篇: 按值删除数组元素的最佳方法