1. Before and after data comparison

// The original data looks like this // the data looks like this after the deduplication[{[{"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"
}]
Copy the code

Two. Use method

  1. Use filter and Map 🌟🌟🌟🌟 service
  2. Use the reduce 🌟 🌟 🌟 🌟
  3. The for loop 🌟 🌟 🌟

Conclusion: There is not much difference between Filter and Reduce in time. Filter is slightly faster, but filter syntax is more concise

1. Use Filter and Map

Simple code, easy to use, 4 lines of code, the shortest average time, five-star recommendation

function uniqueFunc(arr, uniId){
  const res = new Map(a);return arr.filter((item) = >! res.has(item[uniId]) && res.set(item[uniId],1));
}
Copy the code
2. Use the reduce

Slightly more code, average time spent on par with the first, four stars recommended

function uniqueFunc2(arr, uniId){
  let hash = {}
  return arr.reduce((accum,item) = > {
    hash[item[uniId]] ? ' ' : hash[item[uniId]] = true && accum.push(item)
    return accum
  },[])
}
Copy the code
3. Use the for loop

Slightly more time consuming, but average time consuming, recommended by Samsung

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
}
Copy the code

Three.2400 pieces of data, processing time comparison of the three methods

Test times filter Map reduce The for loop
1 0.139892578125 ms 0.19189453125 ms 0.2060546875 ms
2 0.12109375 ms 0.1279296875 ms 0.195068359375 ms
3 0.112060546875 ms 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
Test time screenshot display