Created
December 15, 2013 12:15
-
-
Save sleepyfox/7972277 to your computer and use it in GitHub Desktop.
Finding the intersection of two arrays of similar objects in CoffeeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
I can build this, but I feel sad that I have to build this.
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
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.