Testing Every Element
Problem
You want to be able to check that every element in an array meets a particular condition.
Solution
Use Array.every (ECMAScript 5):
Array.every was added 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.
For a real world example, pretend you have a multiple select list that looks like:
Now you want to verify that the user selected only numbers. Let’s use Array.every:
Discussion
This is similar to using ruby’s Array#all? method.