6

I am trying to find the difference betweeen two arrays of objects using underscore js library.

2
  • underscore in coffeescript, every sain developers nightmare, so I guess simple plain old javascript, like this one is out ? Commented Jul 25, 2014 at 21:00
  • Can you help me convert that to coffeescript? Commented Jul 25, 2014 at 21:22

1 Answer 1

13

Do you want to use the difference function of underscore? You can do this:

_.difference([1, 2, 3, 4, 5], [5, 2, 10])

this works in coffeescript.

EDIT

Using an array of objects and comparing the id property

arrayOne = [{id: 1}, {id: 2}]
arrayTwo =[{id: 2}, {id: 3}]

_.select arrayOne, (item) ->
    !_.findWhere(arrayTwo, {id: item.id})
Sign up to request clarification or add additional context in comments.

3 Comments

ya thats what i want to do but i want to do it for two arrays of objects not integers. Each object has a unique integer ID
Just beware: the order of the arrays matters when using _.difference(). It doesn't show you the items that don't belong to both, it shows you what you have left when you subtract the second array from the first.
Awesome elegant solution. UnderscoreJS really rocks =]

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.