óCoffeeScript Cookbook

数组去重 Removing Duplicate Elements from Arrays

问题 Problem

你想给一个数组去重。

You want to remove duplicate elements from an array.

方法 Solution

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

[1,1,2,2,2,3,4,5,6,6,6,"a","a","b","d","b","c"].unique()
# => [ 1, 2, 3, 4, 5, 6, 'a', 'b', 'd', 'c' ]

讨论 Discussion

JavaScript中有很多中unique方法的实现。这里的这个实现基于”The fastest method to find unique items in array”,在这里可以找到。 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.

注意: 尽管这在常见的语言,比如说Ruby中很常见,但是在JavaScript中扩展原生对象往往被成是不好的实践。(参看: Maintainable JavaScript: Don’t modify objects you don’t own; Extending built-in native objects. Evil or not?)。

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?).