我正在寻找一种有效的方法,从JavaScript数组中删除所有在另一个数组中存在的元素。
// If I have this array:
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// and this one:
var toRemove = ['b', 'c', 'g'];
我希望对myArray进行操作,使其变成这样:['a', 'd', 'e', 'f']
使用jQuery,我正在使用grep()
和inArray()
,这很有效:
myArray = $.grep(myArray, function(value) {
return $.inArray(value, toRemove) < 0;
});
有没有一种纯JavaScript的方法来做到这一点,而不需要使用循环和切割(splicing)?
.filter()
这样的函数式方法。相反,你会使用for
循环。如果原始顺序不需要保持,你可以避免使用.splice()
。或者,如果你认为有很多项需要删除,也有办法使.splice()
更加高效。 - Blue Skies