当前位置:网站首页>对象数组去重
对象数组去重
2022-06-25 22:09:00 【wen_文文】
var tmp = [{
id: 1,
value: 'a'
},
{
"id": 2,
"value": "b"
},
{
"id": 1,
"value": "a"
}
]
// 根据数组元素的id判断该元素是否已存在
// 方法1
function arrayRemval(arr) {
let result = [];
let obj= {};
for(let i=0;i<arr.length;i++) {
let item = arr[i];
if(!obj[item.id]) {
result.push(item)
obj[item.id] = true;
}
}
return result;
}
// 方法2
function arrayRemval(arr) {
let result = [];
let keys= []
for(let i=0;i<arr.length;i++) {
let item = arr[i];
if(!keys.includes(item.id)) {
result.push(item)
keys.push(item.id);
}
}
return result;
}
console.log(arrayRemval(tmp)); //(2) [{id: 1, value: "a"},{id: 2, value: "b"}]
// 业务中的需求,将分组中的商品去重
let selectedGroup= [
{id: '1',name:'水果类',productList:[
{productId:'001',productName:'苹果'},
{productId:'002',productName:'香蕉'},
{productId:'003',productName:'橘子'},
]},
{id: '2',name:'护肤品类',productList:[
{productId:'004',productName:'葡萄'},
{productId:'005',productName:'芒果'},
{productId:'003',productName:'橘子'},
]}
]
function uniqe() {
let list = []; //二维数组
let productList = [] //存放去重后的商品
selectedGroup.forEach(ele=>{
list.push(ele.productList)
})
let productIdList = []; //用于记录当前有效的商品元素id
list.forEach(ele=>{
if(ele.length>0) {
ele.forEach(product=>{
if(!productIdList.includes(product.productId)) {
productIdList.push(product.productId)
productList.push(product)
}
})
}
})
return productList
}
let result = uniqe()
边栏推荐
- Gradle的环境安装与配置
- Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)
- final和static
- C# IO Stream 流(一)基础概念_基本定义
- B. Box Fitting-CodeCraft-21 and Codeforces Round #711 (Div. 2)
- Kotlin null pointer bug
- MySQL自定义函数实例
- 第五章 习题(124、678、15、19、22)【微机原理】【习题】
- Download the latest V80 version of Google Chrome
- 发送邮件工具类
猜你喜欢
随机推荐
idea 查看单元测试覆盖率
第六章 习题(678)【微机原理】【习题】
C1. k-LCM (easy version)-Codeforces Round #708 (Div. 2)
请问可以不部署服务端实现图片上传吗?
php中使用Makefile编译protobuf协议文件
Object类常用方法
如何进行流程创新,以最经济的方式提升产品体验?
UE4 learning record 2 adding skeleton, skin and motion animation to characters
Analysis on the control condition and mode of go cooperation overtime exit
On the quantity control mechanism of swoole collaboration creation in production environment
js实现输入开始时间和结束时间,输出其中包含多少个季,并且把对应年月打印出来
虚析构和纯虚析构及C ++实现
数据同步
今天说说String相关知识点
Blob
说说单例模式!
mysql
php性能优化
Kotlin null pointer bug
final和static









