js对象数组合并并去重
时间: 2023-10-25 07:26:56 浏览: 102
数组合并去重
在JavaScript中,可以使用以下代码来合并和去重对象数组:
```javascript
function mergeAndDistinct(jsonArray1, jsonArray2) {
let mergedArray = jsonArray1.concat(jsonArray2);
let distinctArray = [];
for (let i = 0; i < mergedArray.length; i++) {
let flag = true;
for (let j = 0; j < distinctArray.length; j++) {
if (JSON.stringify(mergedArray[i]) === JSON.stringify(distinctArray[j])) {
flag = false;
break;
}
}
if (flag) {
distinctArray.push(mergedArray[i]);
}
}
return distinctArray;
}
```
这段代码接受两个对象数组作为参数,将它们合并为一个数组,并去除重复的对象。它使用嵌套的循环来比较每个对象是否已存在于新数组中,如果不存在,则将其添加到新数组中。最后,返回新数组作为结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [JS对象数组合并去重?](https://blog.csdn.net/weixin_35696012/article/details/114317473)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [Javascript 【基础】对象数组去重](https://blog.csdn.net/qq_31254489/article/details/109540976)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文