删除另一个数组中包含的所有元素 [英] Remove all elements contained in another array
本文介绍了删除另一个数组中包含的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种有效的方法来从 javascript 数组中删除所有存在于另一个数组中的元素.
I am looking for an efficient way to remove all elements from a javascript array if they are present in another array.
// 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']
I want to operate on myArray to leave it in this state: ['a', 'd', 'e', 'f']
对于 jQuery,我使用 grep()
和 inArray()
,效果很好:
With jQuery, I'm using grep()
and inArray()
, which works well:
myArray = $.grep(myArray, function(value) {
return $.inArray(value, toRemove) < 0;
});
是否有一种纯 javascript 的方式来做到这一点而无需循环和拼接?
Is there a pure javascript way to do this without looping and splicing?
推荐答案
使用 Array.filter()
方法:
Use the Array.filter()
method:
myArray = myArray.filter( function( el ) {
return toRemove.indexOf( el ) < 0;
} );
<小时>
小改进,因为浏览器支持 Array.includes()
增加了:
myArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
} );
<小时>
使用箭头函数的下一次改编:
myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );
这篇关于删除另一个数组中包含的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文