Functional Programming - Implement the filter Method on a Prototype

Hello everyone, i want to know something, to make it clear, look at the code in the photo:


I found this solution by FCC team, i want to know why did they wrote

If (Boolean(callback(this[B], B, this)))

and why exactly this order, for example why not write

if (Boolean(callback(this[B], this, B)));

Challenge Information:

Functional Programming - Implement the filter Method on a Prototype

1 Like

This depends on the parameters order, that is expected for callback function to have.

In this case there’s also the goal of the challenge - to implement own filter method. The original method is expecting callback function accepting parameters in this order:

1 Like

This specific problem is also confusing me and for similar reasons–but this thread is helping me to understand a little bit more.

Thank you, sanity (ha) for the documentation link.

This link within that link helped me to demystify what’s happening here, somewhat.

These “iterative methods” (map, filter, indexOf and others) which arrays have in Javascript often times take a callback function. That callback function can be named anything. In this solution, it’s called callback… probably for illustrative, clear purposes.

For the filter() method the callback function takes three arguments in this order:
callback(element, index, array).
element meaning current element being processed in the array.
index meaning the index of that element being processed.
array meaning the array that the method was called upon.

for other methods, like reduce(), the callback function takes a different set of arguments

The callback function will be performed on elements in the array that the iterative method was called on.

The filter() method returns an array.

In this solution, the filter method executes the “For” statement, which contains an “If” Statement. For each iteration of i, if the callback function returns true, push this[i] into the new array. Don’t push i (that will be 0, 1, 2, 3 …) don’t push this (that will be the array).

Someone, please correct me if I’m wrong–or help me to expand upon my understanding. Thank you.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.