# JS对象数组去重的三种方法

·  阅读 16756

### 一.去重前后数据对比

``````// 原数据是这样的                   // 去重后数据是这样的
[{                                [{
"goodsId": "1",                    "goodsId": "1",
"quota": 12,                       "quota": 12,
"skuId": "1"                       "skuId": "1"
},                                 },
{                                  {
"goodsId": "2",                    "goodsId": "2",
"quota": 12,                       "quota": 12,
"skuId": "2"                       "skuId": "2"
},                                 }]
{
"goodsId": "1",
"quota": 12,
"skuId": "1"
}]

### 二.使用方法

1. 使用filter和Map 🌟🌟🌟🌟🌟
2. 使用reduce 🌟🌟🌟🌟
3. for循环 🌟🌟🌟

##### 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
}

### 三.2400条数据，三种方法处理时间对比

10.139892578125 ms0.19189453125 ms0.2060546875 ms
20.12109375 ms0.1279296875 ms0.195068359375 ms
30.112060546875ms0.11767578125 ms0.174072265625 ms
40.10400390625 ms0.1728515625 ms0.18701171875 ms
50.10986328125 ms0.12890625 ms0.175048828125 ms
60.113037109375 ms0.10791015625 ms0.172119140625 ms
70.134033203125 ms0.129150390625 ms0.172119140625 ms