Javascript数组:删除其他数组中包含的所有元素

我正在寻找一种有效的方法来从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.filter()方法:

 myArray = myArray.filter( function( el ) { return toRemove.indexOf( el ) < 0; } ); 

浏览器对Array.includes()支持有所增加:

 myArray = myArray.filter( function( el ) { return !toRemove.includes( el ); } ); 

filter方法应该做的伎俩:

 const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; const toRemove = ['b', 'c', 'g']; // ES5 syntax const filteredArray = myArray.filter(function(x) { return toRemove.indexOf(x) < 0; }); 

如果你的toRemove数组很大,这种查找模式可能是低效的。 创build一个映射的性能会更好,这样查找就是O(1)而不是O(n)

 const toRemoveMap = toRemove.reduce( function(memo, item) { memo[item] = memo[item] || true; return memo; }, {} // initialize an empty object ); const filteredArray = myArray.filter(function (x) { return toRemoveMap[x]; }); // or, if you want to use ES6-style arrow syntax: const filteredArray = myArray.filter(x => toRemoveMap[x]); 

如果您正在使用一组对象。 然后下面的代码应该做的魔术,其中一个对象属性将成为删除重复项目的条件。

在下面的例子中,删除了重复项目,比较每个项目的名称。

试试这个例子。 http://jsfiddle.net/deepak7641/zLj133rh/

 var myArray = [ {name: 'deepak', place: 'bangalore'}, {name: 'chirag', place: 'bangalore'}, {name: 'alok', place: 'berhampur'}, {name: 'chandan', place: 'mumbai'} ]; var toRemove = [ {name: 'deepak', place: 'bangalore'}, {name: 'alok', place: 'berhampur'} ]; for( var i=myArray.length - 1; i>=0; i--){ for( var j=0; j<toRemove.length; j++){ if(myArray[i] && (myArray[i].name === toRemove[j].name)){ myArray.splice(i, 1); } } } alert(JSON.stringify(myArray)); 

Lodash也有一个实用的function: https ://lodash.com/docs#difference

如果你不能使用新的ES5的东西这样的filter我认为你被困在两个循环:

 for( var i =myArray.length - 1; i>=0; i--){ for( var j=0; j<toRemove.length; j++){ if(myArray[i] === toRemove[j]){ myArray.splice(i, 1); } } } 

ECMAScript 6集可用于计算两个数组的不同元素:

 const myArray = new Set(['a', 'b', 'c', 'd', 'e', 'f', 'g']); const toRemove = new Set(['b', 'c', 'g']); const difference = new Set([...myArray].filter((x) => !toRemove.has(x))); console.log(Array.from(difference)); // ["a", "d", "e", "f"] 

我刚刚实施为:

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