javascript 实现两个数组合并,并且去重。例如var a = [{id:"1",txt:"aa"},{id:"2",txt:"bb"}]; var b = [{id:"1",txt:"aa"},{ix:"3",txt:"cc"}] 如何合并a,b数组并且去重?
时间: 2024-01-16 22:18:55 浏览: 121
JavaScript数组去重的方法总结【12种方法,号称史上最全】
5星 · 资源好评率100%
以下是JavaScript实现两个数组合并并去重的方法:
1. 使用Set数据结构
```javascript
var a = [{id:"1",txt:"aa"},{id:"2",txt:"bb"}];
var b = [{id:"1",txt:"aa"},{ix:"3",txt:"cc"}];
var mergedArray = Array.from(new Set([...a, ...b]));
console.log(mergedArray);
// 输出:[{id:"1",txt:"aa"},{id:"2",txt:"bb"},{ix:"3",txt:"cc"}]
```
2. 使用filter方法和findIndex方法
```javascript
var a = [{id:"1",txt:"aa"},{id:"2",txt:"bb"}];
var b = [{id:"1",txt:"aa"},{ix:"3",txt:"cc"}];
var mergedArray = a.concat(b.filter(item => {
return a.findIndex(i => i.id === item.id) === -1;
}));
console.log(mergedArray);
// 输出:[{id:"1",txt:"aa"},{id:"2",txt:"bb"},{ix:"3",txt:"cc"}]
```
3. 使用reduce方法和find方法
```javascript
var a = [{id:"1",txt:"aa"},{id:"2",txt:"bb"}];
var b = [{id:"1",txt:"aa"},{ix:"3",txt:"cc"}];
var mergedArray = a.reduce((acc, item) => {
if (!acc.find(i => i.id === item.id)) {
acc.push(item);
}
return acc;
}, b);
console.log(mergedArray);
// 输出:[{id:"1",txt:"aa"},{id:"2",txt:"bb"},{ix:"3",txt:"cc"}]
```
阅读全文