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

前端 未结 8 1258
遇见更好的自我
遇见更好的自我 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:32

    You can use the _.uniqBy function

    var array = [ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }, { id: 1, name: 'bill' },{ id: 2, name: 'bill' } ];
    
    var filteredArray = _.uniqBy(array,function(x){ return x.id && x.name;});
    
    console.log(filteredArray)

    In the above example, filtering is based on the uniqueness of combination of properties id & name.

    if you have multiple properties for an object. then to find unique array of objects based on specific properties, you could follow this method of combining properties inside _.uniqBy() method.

提交回复
热议问题