Skip to content

Instantly share code, notes, and snippets.

@sleepyfox
Created December 15, 2013 12:15
Show Gist options
  • Save sleepyfox/7972277 to your computer and use it in GitHub Desktop.
Save sleepyfox/7972277 to your computer and use it in GitHub Desktop.
Finding the intersection of two arrays of similar objects in CoffeeScript
# General pattern for intersection of two arrays of objects:
# collection1.filter collection2.indexOf
#
# Exercise for the reader: much optimisation can be done
myAlbums = [
{ id: 1, title: "The White Album" },
{ id: 2, title: "The Black Album" },
{ id: 3, title: "Hemispheres" },
{ id: 4, title: "Pure Heroine" } ]
herAlbums = [
{ id: 3, title: "Hemispheres" },
{ id: 2, title: "The Black Album" },
{ id: 5, title: "Nevermind"} ]
areAlbumsEqual = (a, b) ->
a.id is b.id
isObjInArray = (arrayOfObj, searchObject, equalityFunction) ->
isFoundYet = (prev, curr) ->
prev or equalityFunction curr, searchObject
arrayOfObj.reduce isFoundYet, false
intersection = (collection1, collection2, equalityFunction) ->
collection1.filter (value) ->
isObjInArray collection2, value, equalityFunction
console.log intersection myAlbums, herAlbums, areAlbumsEqual
@sleepyfox
Copy link
Author

This assumes some sort of ID field that can be used to determine equality, rather than doing a check on each of the objects hasOwnProperty array using a 'for own key, value of' expression, which would be needed in the absence of an ID.

@jbrains
Copy link

jbrains commented Dec 15, 2013

I can build this, but I feel sad that I have to build this.

@jbrains
Copy link

jbrains commented Dec 15, 2013

Oh hey! 11 days ago: jashkenas/underscore#1367

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment