How can I get a unique array based on object property using underscore

前端 未结 8 1194
遇见更好的自我
遇见更好的自我 2020-12-29 18:30

I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?

Eg.



        
8条回答
  •  囚心锁ツ
    2020-12-29 18:52

    Use the uniq function

    var destArray = _.uniq(sourceArray, function(x){
        return x.name;
    });
    

    or single-line version

    var destArray = _.uniq(sourceArray, x => x.name);
    

    From the docs:

    Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

    In the above example, the function uses the objects name in order to determine uniqueness.

提交回复
热议问题