underscore/lodash unique by multiple properties

前端 未结 5 1831
天涯浪人
天涯浪人 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

    There doesn't seem to be a straightforward way to do this, unfortunately. Short of writing your own function for this, you'll need to return something that can be directly compared for equality (as in your first example).

    One method would be to just .join() the properties you need:

    _.uniqBy(myArray, function(elem) { return [elem.a, elem.b].join(); });
    

    Alternatively, you can use _.pick or _.omit to remove whatever you don't need. From there, you could use _.values with a .join(), or even just JSON.stringify:

    _.uniqBy(myArray, function(elem) {
        return JSON.stringify(_.pick(elem, ['a', 'b']));
    });
    

    Keep in mind that objects are not deterministic as far as property order goes, so you may want to just stick to the explicit array approach.

    P.S. Replace uniqBy with uniq for Lodash < 4

提交回复
热议问题