我有两个不同的数组,我想删除第二个数组中存在的第一个数组元素的所有副本。我已经尝试了一些splice和indexOf方法,但未能实现。检查了其他一些帖子,但找不到我正在寻找的东西。这是下面的示例代码。谢谢你们。
let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];
function func(container, removing){
let result = //i want to write a function there which will remove all duplicates of "removing" from "container".
return result; // result = [1, 4, 5]
}
Run Code Online (Sandbox Code Playgroud)
干得好
let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];
let difference = (a, b) => a.filter(x => !b.includes(x));
console.log(difference(container, removing))Run Code Online (Sandbox Code Playgroud)
如果出于某种原因您担心这样做的效率,可以将线性includes检查替换为O(1)Set查找:
let difference = (a, b) => (s => a.filter(x => !s.has(x)))(new Set(b))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |