Find Duplicate Array within Array

前端 未结 5 1603
野趣味
野趣味 2021-01-05 22:06

Given an array of arrays, what would be the efficient way of identifying the duplicate item?

var array = [
  [
    11.31866455078125,
    44.53836644772605
          


        
5条回答
  •  隐瞒了意图╮
    2021-01-05 22:46

    You can just use plain javascript to do that, it's not that hard, here is my implementation

    for (let i = 0; i < array.length; i++) {
      for (let j = i + 1; j < array.length; j++) {
      
         // quick elimination by comparing sub-array lengths
         if (array[i].length !== array[j].length) {
            continue;
         }
         // look for dupes
         var dupe = true;
         for (var k = 0; k < array[i].length; k++) {
           if (array[i][k] !== array[j][k]) {
             dupe = false;
             break;
           }
         }
         // if a dupe then print
         if (dupe) {
             console.debug("%d is a dupe", j); 
         }
       }
     }
    

    The nice part about this implementation is that it will print you multiple times that an array at an index is a dupe for multiple dupes, you can use that fact to count your dupes in each index!

    This is actually a very efficient way to do this because the inner for loop (j) always runs from the next position of the outer loop (i). so you half your check count.

    And here is a plunk

提交回复
热议问题