0

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 .

3
  • What if there are matching ID's, but no objects with deny:true, only deny:false? What I'm really asking is, can we just remove anything that is deny:false and filter the rest ? Commented Aug 11, 2014 at 7:48
  • so it return deny:false Commented Aug 11, 2014 at 7:55
  • I don't think unique is going to help you, because the time you applied uniq it will filter the duplicates. Commented Aug 11, 2014 at 7:57

1 Answer 1

2

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.

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.