时间:2021-08-15 09:34:26 | 栏目:JavaScript代码 | 点击:次
// 原数据是这样的 // 去重后数据是这样的 [{ [{ "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" }]
结论:filter和Reduce时间上差别不是太大,filter稍微更快一些,但是filter语法更简洁
代码简洁,好用,4行代码搞定,平均耗费时间最短,五星推荐
function uniqueFunc(arr, uniId){ const res = new Map(); return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1)); }
代码稍多,平均耗费时间和第一不分伯仲,四星推荐
function uniqueFunc2(arr, uniId){ let hash = {} return arr.reduce((accum,item) => { hash[item[uniId]] ? '' : hash[item[uniId]] = true && accum.push(item) return accum },[]) }
耗费时间较一二稍多,但是耗费时间平均,三星推荐
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 }
测试次数 | filter Map | reduce | for循环 |
---|---|---|---|
1 | 0.139892578125 ms | 0.19189453125 ms | 0.2060546875 ms |
2 | 0.12109375 ms | 0.1279296875 ms | 0.195068359375 ms |
3 | 0.112060546875ms | 0.11767578125 ms | 0.174072265625 ms |
4 | 0.10400390625 ms | 0.1728515625 ms | 0.18701171875 ms |
5 | 0.10986328125 ms | 0.12890625 ms | 0.175048828125 ms |
6 | 0.113037109375 ms | 0.10791015625 ms | 0.172119140625 ms |
7 | 0.134033203125 ms | 0.129150390625 ms | 0.172119140625 ms |
测试时间截图展示