我正在寻找一种有效的方法,从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的方法来做到这一点没有循环和剪接?


当前回答

我只是实现为:

Array.prototype.exclude = function(list){
        return this.filter(function(el){return list.indexOf(el)<0;})
}

使用:

myArray.exclude(toRemove);

其他回答

现在是一行代码:

Console.log (['a', 'b', 'c', 'd', 'e', 'f', 'g']。filter(x => !~['b', 'c', 'g'].indexOf(x)))

可能无法在旧浏览器上运行。

//Using the new ES6 Syntax console.log(["a", "b", "c", "d", "e", "f", "g"].filter(el => !["b", "c", "g"].includes(el))); // OR // Main array let myArray = ["a", "b", "c", "d", "e", "f", "g"]; // Array to remove const toRemove = ["b", "c", "g"]; const diff = () => (myArray = myArray.filter((el) => !toRemove.includes(el))); console.log(diff()); // [ 'a', 'd', 'e', 'f' ] // OR const diff2 = () => { return myArray = myArray.filter((el) => !toRemove.includes(el)); }; console.log(diff2()); // [ 'a', 'd', 'e', 'f' ]

我只是实现为:

Array.prototype.exclude = function(list){
        return this.filter(function(el){return list.indexOf(el)<0;})
}

使用:

myArray.exclude(toRemove);

ECMAScript 6集合可以更快地计算一个数组中不在另一个数组中的元素:

const myArray = [a, b, c, d, e, f, g的); const toRemove = new Set(['b', 'c', 'g']); const difference = myArray。toRemove.has(x)); console.log(差异);// ["a", "d", "e", "f"]

因为现在V8引擎浏览器使用的查找复杂度是O(1),所以整个算法的时间复杂度是O(n)。

Lodash也有一个效用函数: https://lodash.com/docs#difference