underscore/lodash unique by multiple properties

前端 未结 5 1827
天涯浪人
天涯浪人 2020-12-14 01:08

I have an array of objects with duplicates and I\'m trying to get a unique listing, where uniqueness is defined by a subset of the properties of the object. For example,

5条回答
  •  盖世英雄少女心
    2020-12-14 01:42

    Use Lodash's uniqWith method:

    _.uniqWith(array, [comparator])

    This method is like _.uniq except that it accepts comparator which is invoked to compare elements of array. The order of result values is determined by the order they occur in the array.The comparator is invoked with two arguments: (arrVal, othVal).

    When the comparator returns true, the items are considered duplicates and only the first occurrence will be included in the new array.


    Example:
    I have a list of locations with latitude and longitude -- some of which are identical -- and I want to see the list of unique locations:

    const locations = [
      {
        name: "Office 1",
        latitude: -30,
        longitude: -30
      },
      {
        name: "Office 2",
        latitude: -30,
        longitude: 10
      },
      {
        name: "Office 3",
        latitude: -30,
        longitude: 10
      }
    ];
    
    const uniqueLocations = _.uniqWith(
      locations,
      (locationA, locationB) =>
        locationA.latitude === locationB.latitude &&
        locationA.longitude === locationB.longitude
    );
    
    // Result has Office 1 and Office 2
    

提交回复
热议问题