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()