如何删除两个javascript数组之间的重复元素? [英] How to delete duplicate elements between two javascript arrays?
本文介绍了如何删除两个javascript数组之间的重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a = [
{ id: 1, books: [1, 2, 3, 4] },
{ id: 2, books: [1, 2, 3] },
{ id: 3, books: [1, 2, 3, 4, 5] },
{ id: 9, books: [1, 2] }
];
b = [{ id: 2, books: [1, 2, 3] }, { id: 3, books: [1, 2, 3, 4, 5] }];
我要删除数组 b
相同 a
中的 id
个元素。
该怎么做?谢谢。
I want to delete array b
the same id
elements from a
.
How to do that? Thanks.
这意味着:
我想获得 a = [{ id:1,书籍:[1,2,3,4]}]
,删除数组 b
中的相同元素;
I want to get the a = [{id: 1, books: [1,2,3,4]}]
, get rid the same element within array b
;
我的代码是:
const delDuplicate = (a, b) => {
const bLen = b.length;
if (!bLen) return a;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < bLen; j++) {
if (a[i].id === b[j].id) {
const delItem = a.splice(i, 1)[0];
console.log(delItem);
}
}
}
return a;
};
a = delDuplicate(a, b);
它有效,有更好的方法吗?我认为减少
和地图
也许也可以。
It works, is there a better way? I think reduce
and map
maybe work too.
这两个数组不是简单的数组。因此不能使用 a.indexOf(b [i])!== -1
。
These two arrays are not simple array. So can not use a.indexOf(b[i]) !== -1
.
推荐答案
您可以使用 .map()
, .reduce()
, .filter()
, .indexOf()
var ids = b.map(o => o.id);
a = a.reduce((res, o) =>
[...res] = [...res.filter(Boolean), ids.indexOf(o.id) < 0 && o], []);
var a = [{id: 1, books: [1,2,3,4]}, {id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}, {id: 9, books: [1,2]}];
var b = [{id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}];
var ids = b.map(o => o.id);
a = a.reduce((res, o) =>
[...res] = [...res.filter(Boolean), ids.indexOf(o.id) < 0 && o], []);
console.log(a);
这篇关于如何删除两个javascript数组之间的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文