Skip to content

Commit ada9eb3

Browse files
committed
Array.every recipe
1 parent 68f5867 commit ada9eb3

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
---
2+
layout: recipe
3+
title: Testing Every Element
4+
chapter: Arrays
5+
---
6+
## Problem
7+
8+
You want to be able to check that every element in an array meets a particular condition.
9+
10+
## Solution
11+
12+
Use Array.every (ECMAScript 5):
13+
14+
{% highlight coffeescript %}
15+
evens = (x for x in [1..10] by 2)
16+
17+
evens.every (x)-> x % 2 == 0
18+
# => true
19+
{% endhighlight %}
20+
21+
Array.every was addded to Mozilla's Javascript 1.6 and made standard with EcmaScript 5. If you to support browsers that do not implement EC5 then check out [`_.all` from underscore.js][underscore].
22+
23+
For a real world example, prentend you have a multiple select list that looks like:
24+
25+
{% highlight html %}
26+
<select multiple id="my-select-list">
27+
<option>1</option>
28+
<option>2</option>
29+
<option>Red Car</option>
30+
<option>Blue Car</option>
31+
</select>
32+
{% endhighlight %}
33+
34+
Now you want to verify that the user selected only numbers. Let's use Array.every:
35+
36+
{% highlight coffeescript %}
37+
validateNumeric = (item)->
38+
parseFloat(item) == parseInt(item) && !isNaN(item)
39+
40+
values = $("#my-select-list").val()
41+
42+
values.every validateNumeric
43+
{% endhighlight %}
44+
45+
## Discussion
46+
47+
This is similar to using ruby's Array#all? method.
48+
49+
[underscore]: http://documentcloud.github.com/underscore/

0 commit comments

Comments
 (0)