Removing duplicate objects using Underscore for Javascript in Coffeescript

underscore
Below an example to show how to remove duplicate objects from an array using underscore in Coffeescript.

My answer is based on the following stackoverflow q/a: http://stackoverflow.com/a/9923961/1688441

array=  _.uniq(_.collect(initialArray, (x) ->  JSON.stringify x  )).map((v) -> JSON.parse(v))

The collect underscore method is an alias for map (similar to forEach logic).
We iterate over the elements of the array, and create a new array of Strings (where each object has been converted to a JSON string).

The uniq method returns an array with only the distinct/unique strings.

Finally, we use map to iterate again over the array and reparse the strings to produce an array of distinct JSON objects.



Menelaos Bakopoulos

Mr. Menelaos Bakopoulos is currently pursuing his PhD both at Center for TeleInFrastruktur (CTiF) at Aalborg University (AAU) in Denmark and Athens Information Technology (AIT) in Athens, Greece. He received a Master in Information Technology and Telecommunications Systems from Athens Information Technology and a B.Sc. in Computer Science & Management Information Systems from the American College of Thessaloniki. Since April 2008 he has been a member of the Multimedia, Knowledge, and Web Technologies Group.

More Posts