Find Duplicate Array within Array

前端 未结 5 1651
野趣味
野趣味 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:50

    I believe constructing a LUT is one of the most efficient ways when it comes to making comparisons. The following method constructs a LUT by utilizing Array.prototype.reduce() and eventually mutates the original array by removing not only one but all duplicate elements regardless of how many there are.

    var arr = [
      [
        11.31866455078125,
        44.53836644772605
      ],
      [
        11.31866455078125,
        44.53836644772605
      ],
      [
        11.371536254882812,
        44.53836644772605
      ],
      [
        11.371536254882812,
        44.50140292110874
      ]
    ];
    arr.reduce((p,c,i)=> { var prop = c[0]+"" + c[1]+"";
                           p[prop] === void 0 ? p[prop] = i : p.dups.push(i);
                           return p;
                         },{dups:[]}).dups.reverse().forEach( i => arr.splice(i,1))
    
    document.write('
    ' + JSON.stringify(arr, 0, 2) + '
    ');

    However if you would like to have a new array by keeping the original then obviously it would be much faster procedure.

提交回复
热议问题