gpt4 book ai didi

javascript - 删除另一个数组中包含的所有元素

转载 作者:IT老高 更新时间:2023-10-28 13:16:17 25 4
gpt4 key购买 nike

如果它们存在于另一个数组中,我正在寻找一种从 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 );
} );

使用 arrow functions 进行下一次改编:

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

关于javascript - 删除另一个数组中包含的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19957348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com