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 12:18:55 浏览: 29
以下是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"}]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)