I'm working through JavaScript: The Definitive Guide as part of Learn JavaScript Properly, and I'm having trouble reasoning about the filter()
method in Chapter 7's section on Array Methods.
Here's the example provided:
The
filter()
method returns an array containing a subset of the
elements of the array on which it is invoked. The function you pass to
it should be predicate: a function that returns true or false. The
predicate is invoked just as forforEach()
andmap()
. If the return
value is true, or a value that converts to true, then the element
passed to the predicate is a member of the subset and is added to the
array that will become the return value.
Examples:
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]
Where I'm getting confused is how exactly i
is applied to x
in the the everyother
line. Here's what I think is happening:
i
(the index ofa[]
) is being passed through the function ,x
, which applies the predicate to each element ofa[]
and returns[4, 2]
.Then the function says filter
[4, 2]
out ofa[]
...I'm real fuzzy on how.
When I mess around in the console, I've tried:
everyother = a.filter(function(i) { return i%2==0 }); // returns [4, 2]
which is what I would expect, but I don't understand what happens internally in how JS handles the parameters when I change the above code to
everyother = a.filter(function(x,i) { return i%2==0 }); // returns [5, 3, 1]
(I do know that the array methods are applied like so: function(element, index, array)
)
For this particular example, it's obvious to me that I could get the expected result another way:
everyother = a.filter(function(x) { return x%2!=0 }); // returns [5, 3, 1]
But I suspect that line of thinking is precisely missing the point the example is trying to get across...I'm just missing it.