0

Confusing title, the only simple way to explain is to show you what I'm after :

var user = [
  {foo:"test",bar:1},
  {foo:"test2",bar:2}
];

var items = [{foo:"test",bar:1},{foo:"test4",bar:4},{foo:"test5",bar:5}]

What I want, is to pick one item from items which is not already in user, and add it to user. In this case the user object would end up looking like :

user = [
  {foo:"test",bar:1},
  {foo:"test2",bar:2},
  {foo:"test4",bar:4}
];

I've tried all sorts of _.filter, _.contains, etc... combinations, but can't quite figure it out. Any help would be very appreciated!

2
  • Why test4 but not test5? Commented Dec 1, 2014 at 23:28
  • cus that would be selfish if one user would take all the items ;) could be one or the other though, it makes no difference. Commented Dec 1, 2014 at 23:30

1 Answer 1

1

The logic is as follows: you want to find the first item that is not contained within the user array.

So you can do the following:

var item = _.find(items, function (item) {
    return !_.findWhere(user, item);
});

jsFiddle Demo

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

1 Comment

Wow, that's pretty, I was already starting to write an ugly for loop to do the job. Thanks!

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.