Find Duplicate Array within Array

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

    Lodash gives a lot of useful functions to achieve finding the first duplicate index.
    Using the _.findIndex() and _.isEqual() the following code will find the first duplicate index:

    var duplicateIndex = _.findIndex(array, function(value, index, collection) {
      var equal = _.isEqual.bind(undefined, value);
      return _.findIndex(collection.slice(0, index), equal) !== -1;
    });
    

    or a bit faster but more verbose:

    var duplicateIndex = _.findIndex(array, function(value, index, collection) {
      var equal = _.isEqual.bind(undefined, value);
      return _.findIndex(collection, function(val, ind) {
         return ind < index && equal(val);
      }) !== -1;
    });
    

    Notice that if no duplicate exists, -1 will be returned.
    In a few words the algorithm iterates through array and looks back if the current element does not exist already. If it does, just return the current iteration index.
    Please check the working demo.

提交回复
热议问题