删除另一个数组中包含的所有元素 [英] Remove all elements contained in another array

查看:485
本文介绍了删除另一个数组中包含的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


由于浏览器支持 Array.includes() 增加了:


Small improvement, as browser support for Array.includes() has increased:

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


使用箭头功能进行的下一次改编:


Next adaptation using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

这篇关于删除另一个数组中包含的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆