Javascript 从数组中删除匹配特定字符串的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35249774/
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
Remove all elements from array that match specific string
提问by Kunok
What is the easiest way to remove all elements from array that match specific string? For example:
从匹配特定字符串的数组中删除所有元素的最简单方法是什么?例如:
array = [1,2,'deleted',4,5,'deleted',6,7];
array = [1,2,'deleted',4,5,'deleted',6,7];
I want to remove all 'deleted'
from the array.
我想'deleted'
从数组中删除所有内容。
回答by Walter Chapilliquen - wZVanG
Simply use the Array.prototype.filter()function for obtain elements of a condition
只需使用Array.prototype.filter()函数来获取条件的元素
var array = [1,2,'deleted',4,5,'deleted',6,7];
var newarr = array.filter(function(a){return a !== 'deleted'})
Update: ES6 Syntax
更新:ES6 语法
let array = [1,2,'deleted',4,5,'deleted',6,7]
let newarr = array.filter(a => a !== 'deleted')
回答by Piyush Sagar
If you have multiple strings to remove from main array, You can try this
如果你有多个字符串要从主数组中删除,你可以试试这个
// Your main array
var arr = [ '8','abc','b','c'];
// This array contains strings that needs to be removed from main array
var removeStr = [ 'abc' , '8'];
arr = arr.filter(function(val){
return (removeStr.indexOf(val) == -1 ? true : false)
})
console.log(arr);
// 'arr' Outputs to :
[ 'b', 'c' ]
OR
或者
Better Performance(Using hash), If strict type equality not required
更好的性能(使用哈希),如果不需要严格的类型相等
// Your main array
var arr = [ '8','deleted','b','c'];
// This array contains strings that needs to be removed from main array
var removeStr = [ 'deleted' , '8'];
var removeObj = {}; // Use of hash will boost performance for larger arrays
removeStr.forEach( e => removeObj[e] = true);
var res = arr.filter(function(val){
return !removeObj[val]
})
console.log(res);
// 'arr' Outputs to :
[ 'b', 'c' ]
回答by NG.
array = array.filter(function(s) {
return s !== 'deleted';
});
回答by brk
If you want the same array then you can use
如果你想要相同的数组,那么你可以使用
var array = [1,2,'deleted',4,5,'deleted',6,7];
var index = "deleted";
for(var i = array.length - 1; i >= 0; i--) {
if(array[i] === index) {
array.splice(i, 1);
}
}
else you can use Array.prototype.filter
which creates a new array with all elements that pass the test implemented by the provided function.
否则,您可以使用Array.prototype.filter
它创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。
var arrayVal = [1,2,'deleted',4,5,'deleted',6,7];
function filterVal(value) {
return value !== 'deleted';
}
var filtered = arrayVal.filter(filterVal);