óCoffeeScript Cookbook

Removing Duplicate Elements from Arrays


You want to remove duplicate elements from an array.


Array::unique = ->
  output = {}
  output[@[key]] = @[key] for key in [0...@length]
  value for key, value of output

# => [ 1, 2, 3, 4, 5, 6, 'a', 'b', 'd', 'c' ]


There are many implementations of the unique method in JavaScript. This one is based on “The fastest method to find unique items in array” found here.

Note: Although it’s quite common in languages like Ruby, extending native objects is often considered bad practice in JavaScript (see: Maintainable JavaScript: Don’t modify objects you don’t own; Extending built-in native objects. Evil or not?).