Skip to content

Commit 017b657

Browse files
committed
add Shuffling Array Elements recipe
1 parent aa730dd commit 017b657

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
layout: recipe
3+
title: Shuffling Array Elements
4+
chapter: Arrays
5+
---
6+
## Problem
7+
8+
You want to shuffle the elements in an array.
9+
10+
## Solution
11+
12+
The JavaScript Array `sort()` method accepts a custom sort function. We can write a `shuffle()` method to add some convenience.
13+
14+
{% highlight coffeescript %}
15+
Array::shuffle = -> @sort -> 0.5 - Math.random()
16+
17+
[1..9].shuffle()
18+
# => [ 3, 1, 5, 6, 4, 8, 2, 9, 7 ]
19+
{% endhighlight %}
20+
21+
## Discussion
22+
23+
For more background on how this shuffle logic works, see this [discussion at StackOverflow](http://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling).

0 commit comments

Comments
 (0)