When you call filter using a function of two arguments, the first argument is bound to the value of the array element, the second (optional) to the index of the element.
Your confusion stems from the fact that the input array [5,4,3,2,1] somewhat specific - elements that even have indices (5, 3, 1) are odd, and elements with odd indices (4, 2 ) are even.
Thus, this filtering predicate ...%2 always selects elements of the same type, depending on what you pass as a parameter to the predicate (value or index), you will get odd or even elements.
My advice on clearing up the confusion is to select a different array to test your filtering method. The array should mix the weirdness of the indices and values, something like [1,3,4,5,7,8] . You will immediately notice what happens when a predicate takes into account a value or index.
Also remember that when creating a filter predicate, the names of formal parameters are arbitrary, which matters for their position. The first parameter, no matter what you call it, means the value, the second is the index. If you accidentally run into parameter names and you call your first parameter i , and then your second parameter i , then it communicates with something else in both scenarios.
source share