Find Duplicate Array within Array

前端 未结 5 1605
野趣味
野趣味 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 don't know how to do this other than to just write the algorithm yourself. Both this answer and the other posted ones aren't very efficient but should be fine:

    function findIndex(array, startingIndex, value) {
      var predicate = _.partial(_.isEqual, value);
      var arraySubset = array.slice(startingIndex+1);
      var index = arraySubset.findIndex(predicate);
      return index === -1 ? index : index+startingIndex+1;
    }
    
    function findDuplicates(array) {
      return array.map((value, index) => {
        return {
          value,
          index: findIndex(array, index, value)
        };
      }).filter(info => info.index !== -1);
    }
    
    findDuplicates([1, 2, 3, 4, 1, [ 3 ], [ 4 ], [ 3 ] ]);
    
    // [ { value: 1, index: 4 }, { value: [ 3 ], index: 7 } ]    // [ { value: 1, index: 4 }, { value: [ 3 ], index: 7 } ]
    

    This basically creates a map of the array, calling .findIndex() on the remainder of the array, noting down the index of any duplicates, returning information about every item that has a duplicate and what the index of the duplicate is.

    One nice thing about this is that it will work for triplicates or any amount of occurrences of a value.

提交回复
热议问题