underscore/lodash unique by multiple properties

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

    There is a hint in @voithos and @Danail combined answer. How I solved this was to add a unique key on the objects in my array.

    Starting Sample Data

    const animalArray = [
      { a: 4, b: 'cat', d: 'generic' },
      { a: 5, b: 'cat', d: 'generic' },
      { a: 4, b: 'dog', d: 'generic' },
      { a: 4, b: 'cat', d: 'generic' },
    ];
    

    In the example above, I want the array to be unique by a and b but right now I have two objects that have a: 4 and b: 'cat'. By combining a + b into a string I can get a unique key to check by.

    { a: 4, b: 'cat', d: 'generic', id: `${a}-${b}` }. // id is now '4-cat'
    

    Note: You obviously need to map over the data or do this during creation of the object as you cannot reference properties of an object within the same object.

    Now the comparison is simple...

    _.uniqBy(animalArray, 'id');
    

    The resulting array will be length of 3 it will have removed the last duplicate.

提交回复
热议问题