假设我有一个数组,例如:[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 );
} );
最佳答案
这是使用filter
、indexOf
和splice
实现的方法。
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/