JavaScript array iteration methods (Part II)

Our next stop on our trek through Javascript array iteration methods (begun in Part I) is Array#filter. We’ll start by creating a function that takes a value and returns true or false, depending on whether the value is or is not greater than 2:

var greaterThan2 = function (val) { return val > 2; };

We can now filter any array to find all values > 2 by passing greaterThan2 as a callback to Array#filter:

var arr = [0,1,2,3,4];
var arr2 = arr.filter(greaterThan2);

arr2 is now [3,4]. arr is unchanged.

Like most of Javascript Array’s iteration methods, Array#filter passes the array element’s index position as the second argument when it invokes the callback. So you can filter not only on the element’s value but also on its position within the array. To see this, we’ll create a callback that returns true if and only if the element’s array index is < 3 (i.e., 0, 1 or 2):

var first3Elements = function (val, index) { return index < 3; };

Then we filter the array based on this callback:

var arr3 = arr.filter(first3Elements);
JSON.stringify(arr3) === JSON.stringify([0,1,2]) // true

Array#every returns true if and only if the callback function returns true for every value in the array:

arr.every(greaterThan2); // false (because 0, 1 and 2 aren't > 2)

But we can define another callback that will return true for every value in arr:

var lessThan5 = function (val) { return val < 5; };
arr.every(lessThan5);    // true

If you’re interested in whether one or more elements in an array satisfy the callback criteria, you can use Array#some:

arr.some(lessThan5);     // true
arr.some(greaterThan2);  // true

var lessThan0 = function (val) { return val < 0; };
arr.some(lessThan0);     // false

And that completes our tour of JavaScript array’s iteration methods. The one method I did not cover is Array#reduceRight. It’s basically Array#reduce, except that it processes the array starting at the end and working back to the beginning, rather than the other way around. This is pretty unimportant because you could always just call Array#reverse before calling Array#reduce.

Posted by James on Friday, March 22, 2013