JavaScript数组:删除包含在另一个数组的所有元素 [英] Javascript arrays: remove all elements contained in another array
本文介绍了JavaScript数组:删除包含在另一个数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要寻找一种有效的方式,从一个javascript数组中删除所有元素,如果他们在另一个数组present。
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的操作把它留在这个状态: ['一','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?
推荐答案
使用的<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\"><$c$c>Array.filter()$c$c>方法:
myArray = myArray.filter( function( el ) {
return toRemove.indexOf( el ) < 0;
} );
这篇关于JavaScript数组:删除包含在另一个数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文