Reputation: 7919
In my application i have an array like this :
var arr=[
{id:1,name:"mohammmad",deny:false},
{id:1,name:"mohammmad",deny:false},
{id:1,name:"mohammmad",deny:true},
{id:2,name:"ali",deny:false},
{id:3,name:"reza",deny:true},
{id:2,name:"ali",deny:true}
];
now I want to return unique collection of this array based on id
of object but if collection have true
value for deny
it must return the object that have deny=true
. for example :
{id:1,name:"mohammmad",deny:false},
{id:1,name:"mohammmad",deny:false},
{id:1,name:"mohammmad",deny:true},
it filter with id=1
but return the object that have deny=true
.
i also create a jsbin here .
Upvotes: 0
Views: 230
Reputation: 30330
Using underscore:
_.chain(arr)
.sortBy(function(d) { return !d.deny })
.uniq(function(d) { return d.id })
.value()
Sort by deny
(with true values first), then uniq
on id
. Underscore's implementation of uniq
keeps the first matching value for each key. Therefore, if a given id
had a value with deny: true
, that value will be kept. If it didn't, it keeps first value with any value of deny
.
Upvotes: 2