欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS對象數(shù)組去重的3種方法示例及對比

 更新時間:2021年07月15日 16:19:23   作者:光年之外_宇  
這篇文章主要給大家介紹了關(guān)于JS對象數(shù)組去重的3種方法,三種方法分別包括使用filter和Map、使用reduce以及for循環(huán),文中每個方法都給出了示例代碼,需要的朋友可以參考下

一.去重前后數(shù)據(jù)對比

// 原數(shù)據(jù)是這樣的                   // 去重后數(shù)據(jù)是這樣的
[{                                [{
  "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循環(huán)           🌟🌟🌟

結(jié)論:filter和Reduce時間上差別不是太大,filter稍微更快一些,但是filter語法更簡潔

1.使用filter和Map

代碼簡潔,好用,4行代碼搞定,平均耗費時間最短,五星推薦

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循環(huán)

耗費時間較一二稍多,但是耗費時間平均,三星推薦

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條數(shù)據(jù),三種方法處理時間對比

測試次數(shù) filter Map reduce for循環(huán)
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

測試時間截圖展示

總結(jié)

到此這篇關(guān)于JS對象數(shù)組去重的3種方法及對比的文章就介紹到這了,更多相關(guān)JS對象數(shù)組去重內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論