数组对象去重

182 阅读1分钟

一.去重前后数据对比

// 原数据是这样的

[{

"goodsId": "1", "quota": 12, "skuId": "1" },

{ "goodsId": "2", "quota": 12, "skuId": "2" },

{ "goodsId": "1", "quota": 12, "skuId": "1" }]

// 去重后数据是这样的

[{

"goodsId": "1", "quota": 12, "skuId": "1" },

{ "goodsId": "2", "quota": 12, "skuId": "2" }]

二.使用方法

1.使用filter和Map 代码简洁

function uniqueFunc(arr, uniId){

const res = new Map();
return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1)); 

}

2.使用reduce 代码稍多

function uniqueFunc2(arr, uniId){

let hash = {} return arr.reduce((accum,item) => { 
    hash[item[uniId]] ? '' : hash[item[uniId]] = true && accum.push(item) 
return accum },[])

}

3.使用for循环 耗费时间较一二稍多

function uniqueFunc3(arr, uniId){

let obj = {} let tempArr = [] for(var i = 0; i<arr.length; i++){ 
if(!obj[arr[i][uniId]]){
    tempArr.push(arr[i]) obj[arr[i][uniId]] = true }
} 
return tempArr 
}

const books = [

{ name: "My Sister the Serial Killer", author: "Oyinkan Braithwaite" },

{ name: "Educated", author: "Tara Westover" },

{ name: "My Sister the Serial Killer", author: "Oyinkan Braithwaite" }];

function unique(arr) {

let unique = {};
arr.forEach(function(item) {
    unique[JSON.stringify(item,['name','author'])] = item; //键名顺序问题
})

arr = Object.keys(unique).map(function(u) {

//Object.keys()返回对象的所有键值组成的数组,map方法是一个遍历方法,返回遍历结果组成的数组.
//将unique对象的键名还原成对象数组
return JSON.parse(u);
})
return arr;

}

function removeDuplicate_10(arr, attr) {

  const result = new Map(); return arr.filter((item) => !result.has(item[attr]) && result.set(item[attr], 1)) 

}

removeDuplicate_10(数组,重复参数名)