Remove Duplicates from Array in CoffeeScript

Problem

You have an array in CoffeeScript, which contains equal elements multiple times such as:

[1,1,2,3,3]

You would like to have only unique values in the array. Thus, transform it into:

[1,2,3]

Solution

You can use the following method to accomplish such:

removeDuplicates = (ar) ->
  if ar.length == 0
    return []  
  res = {}
  res[ar[key]] = ar[key] for key in [0..ar.length-1]
  value for key, value of res

alert(removeDuplicates([1,2,3,3,4,4,5]));

References

This solution is based on this approach (with a few minor issues fixed).

2 thoughts on “Remove Duplicates from Array in CoffeeScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s