js 算法 兩個數組比較去重,性能優化


如果追求性能,可以采用空間換時間的做法,在JS中最常見的處理方式就是構建Object,因為Object查找key的時間復雜度是O(1),而數組是O(n)

<!DOCTYPE html>
<html>
<head>
    <title>js兩個數組比較去重</title>
</head>
<body>
<script type="text/javascript">
    // 如果追求性能,可以采用空間換時間的做法,在JS中最常見的處理方式就是構建Object,因為Object查找key的時間復雜度是O(1),而數組是O(n)
    const list1 = [
        {id: 0, name: 'xiaomin'},
        {id: 1, name: 'xiaohong'},
    ];
    const list2 = [
        {id: 0, name: 'xiaomin'},
        {id: 1, name: 'xiaohong'},
        {id: 3, name: 'xiaomin'},
        {id: 4, name: 'xiaohong'},
    ];
    // 首先構造Object
    const idSet = list1.reduce((acc, v) => {
        acc[v.id] = true;
        return acc;
    }, {});
    console.log('構造Object', idSet)
    // 遍歷list2,去掉在idSet中存在的id
    const result = list2.filter(v => !idSet[v.id]);
    const repeat = list2.filter(v => idSet[v.id]);
    console.log('去重后的result', result)
    console.log('重復的repeat', repeat)
</script>
</body>
</html>

打印結果:

 

 

<! DOCTYPE  html>
< html>
< head>
  < title>js兩個數組比較去重</ title>
</ head>
< body>
< script  type= "text/javascript">
   // 如果追求性能,可以采用空間換時間的做法,在JS中最常見的處理方式就是構建Object,因為Object查找key的時間復雜度是O(1),而數組是O(n)
   const list1  = [
      {id:  0, name:  'xiaomin'},
      {id:  1, name:  'xiaohong'},
  ];
   const list2  = [
      {id:  0, name:  'xiaomin'},
      {id:  1, name:  'xiaohong'},
      {id:  3, name:  'xiaomin'},
      {id:  4, name:  'xiaohong'},
  ];
   // 首先構造Object
   const idSet  = list1. reduce(( accv=> {
      acc[v.id]  =  true;
       return acc;
  }, {});
   console. log( '構造Object', idSet)
   // 遍歷list2,去掉在idSet中存在的id
   const result  = list2. filter( v  =>  !idSet[v.id]);
   const repeat  = list2. filter( v  => idSet[v.id]);
   console. log( '去重后的result', result)
   console. log( '重復的repeat', repeat)
</ script>
</ body>
</ html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM