JS: Functions
Theory: Filtering
The concept of "filtering" is intuitively clear to everyone. We drink filtered water and filter what we say. It's pretty much the same in programming. The operation "filter" with respect to the collection means that we select from it only those items that satisfy the desired condition. A typical task might look like this - select users over the age of 10:
Filtering is as common as mapping. The overall code scheme for filtering is almost identical to the mapping, except for a couple of key points:
- Filtering returns either the same size collection (if nothing was filtered) or a smaller one. It can even return an empty collection if none of the items fit.
- Filtering always returns the original elements. She never does the mapping. If the filter input received a list of users, the list of users will also be in the output.
Now let's see what filtering looks like using the filter()method:
The function passed to the filter() method must be a predicate. That is, its task is to return either true or false for each item in the collection. The value that is returned is not used in any way - it just tells you whether to include the current element in the resulting array or not. Beginners often make a mistake at this stage and start returning from the filter what they would like to see in the resulting array (you have to use the map() method to do this).
Implementation
Let's write our own function myFilter(), which works similarly to the filter() array method:

