Find Duplicate Array within Array

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

    Here's an approach that uses uniqWith(), and difference():

    _.indexOf(array, _.head(_.difference(array, _.uniqWith(array, _.isEqual))));
    

    The basic idea is:

    1. Use uniqWith() to remove the duplicates from array.
    2. Use difference() to compare array against the duplicate-free version. This gets us an array of the duplicates.
    3. Use head() to get the first item of the array. This is the duplicate that we're interested in.
    4. Use indexOf() to find the index of the duplicate, in this case it's 1.

    However, if you need the index of the original, and not it's duplicate, we have to make some adjustments:

    var duplicate = _.head(_.difference(array, _.uniqWith(array, _.isEqual)));
    _.findIndex(array, _.unary(_.partial(_.isEqual, duplicate)));
    

    We're still using uniqWith(), and difference() to find the duplicate. But now, we're using findIndex() to get the index. The reason is that we need to use isEqual() to find the first position of the duplicate, not the second. We construct the predicate using partial() and unary(). The result this time is 0.

提交回复
热议问题