MBehtemam
MBehtemam

Reputation: 7919

Filter and Unique array of object in javascript with underscore.js based on two property

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

Answers (1)

joews
joews

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.

JSFiddle

Upvotes: 2

Related Questions