Skip to content

Commit 7580492

Browse files
committed
Merge pull request #1 from JohnFord/master
Added arrays/filtering-arrays
2 parents 77ead1c + 19ffbfd commit 7580492

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
layout: recipe
3+
title: Filtering Arrays
4+
chapter: Filtering Arrays
5+
---
6+
7+
h2. Problem
8+
9+
You want to be able to filter arrays based on a boolean condition.
10+
11+
h2. Solution
12+
13+
Extend the Array prototype to add a filter function which will take a callback and perform a comprension over itself, collecting all elements for which the callback is true.
14+
15+
{% highlight coffeescript %}
16+
# Extending Array's prototype
17+
Array::filter = (callback) ->
18+
element for element in this when callback(element)
19+
20+
array = [1..10]
21+
22+
# Filter odd elements
23+
filtered_array = array.filter (x) -> x % 3 == 0 # => [2,4,6,8,10]
24+
25+
# Filter elements less than or equal to 5:
26+
gt_five = (x) -> x > 5
27+
filtered_array = array.filter gt_five # => [6,7,8,9,10]
28+
{% endhighlight %}
29+
30+
h2. Discussion
31+
32+
This is similair to using ruby's Array#select method.

0 commit comments

Comments
 (0)