JavaScript filter() method confusion

When you invoke filter with a function of two arguments, the first argument binds to the array element value, the second (the optional one) to the element index.

Your confusion stems from the fact that the input array [5,4,3,2,1] is somewhat specific - elements that have even indexes (5, 3, 1) are odd and elements that have odd indexes (4, 2) are even.

This makes this filtering predicate ...%2 always pick elements of the same 'kind', depending on what you pass as the predicate parameter (value or index) you will get odd or even elements.

My advice to clean up the confusion would be to pick a different array to test your filtering method. The array should mix oddity of indexes and values, something like [1,3,4,5,7,8]. You will immediately observe what happens when the predicate takes a value or an index into account.

Also remember that when creating a filtering predicate, the names of formal parameters are arbitrary, what matters is their position. The first parameter, no matter how you call it, stands for the value, the second stands for the index. If you clash your parameter names by accident and you call your first parameter i and then your second parameter i then it binds to something else in both scenarios.


Your example is really simple and clear:

a = [5, 4, 3, 2, 1];
smallvalues = a.filter(function(x) { return x < 3 });   // [2, 1]
everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1]

The first one reads: »return me every element (x), which is lesser than 3«. The result is not astounding.

The second one reads: »return me every element, whose index (i) is even (including 0)«

The x is just ignored.

You could also have written [5, 4, 3, 2, 1].filter(function(_,x){return x%2===0})

See MDN for Array.prototype.filter().

Tags:

Javascript