gpt4 book ai didi

javascript - 如何从 JS 中的数组中删除一个子集?

转载 作者:行者123 更新时间:2023-11-30 14:10:08 39 4
gpt4 key购买 nike

假设我有一个数组,例如:[1, 1, 2, 2, 3, 3, 4, 5]
我想删除这个元素数组 [1, 2, 3, 4, 5]
所以最后我想留下 [1, 2, 3]

我试过使用下面的方法,但它从主数组中删除了元素的所有副本。

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

最佳答案

这是使用filterindexOfsplice 实现的方法。

const input = [1, 1, 2, 2, 3, 3, 4, 5];

function removeSubset(arr, subset) {
const exclude = [...subset];
return arr.filter(x => {
const idx = exclude.indexOf(x);
if (idx >= 0) {
exclude.splice(idx, 1);
return false;
}
return true;
});
}

console.log(removeSubset(input, [1, 2, 3, 4, 5]));

关于javascript - 如何从 JS 中的数组中删除一个子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618504/

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