I am trying to find the difference betweeen two arrays of objects using underscore js library.
Asked
Active
Viewed 8,155 times
6
-
underscore in coffeescript, every sain developers nightmare, so I guess simple plain old javascript, like [**this one**](http://stackoverflow.com/questions/6715641/an-efficient-way-to-get-the-difference-between-two-arrays-of-objects) is out ? – adeneo Jul 25 '14 at 21:00
-
Can you help me convert that to coffeescript? – compsci45000 Jul 25 '14 at 21:22
1 Answers
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})

Gabriel
- 473
- 4
- 11
-
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 – compsci45000 Jul 25 '14 at 22:00
-
2Just 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. – Michael Oryl Jul 20 '15 at 10:21
-