Skip to content

Commit b746ee1

Browse files
committed
add recipe Removing duplicate elements from Arrays
1 parent 49838fa commit b746ee1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
layout: recipe
3+
title: Removing duplicate elements from Arrays
4+
chapter: Arrays
5+
---
6+
## Problem
7+
8+
You want to remove duplicate elements from an array.
9+
10+
## Solution
11+
12+
{% highlight coffeescript %}
13+
Array::unique = ->
14+
o = {}
15+
r = []
16+
o[this[i]] = this[i] for i in [1...@length]
17+
r.push(v) for k,v of o
18+
r
19+
20+
[1,1,2,2,2,3,4,5,6,6,6,"a","a","b","d","b","c"].unique()
21+
# => [ 1, 2, 3, 4, 5, 6, 'a', 'b', 'd', 'c' ]
22+
{% endhighlight %}
23+
24+
## Discussion
25+
26+
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](http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/).

0 commit comments

Comments
 (0)