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:
const users = [
{ name: 'John', age: 19 },
{ name: 'Richard', age: 1 },
{ name: 'Antony', age: 4 },
{ name: 'Alex', age: 16 },
];
const result = [];
for (const user of users) {
if (user.age > 10) {
result.push(user);
}
}
console.log(result);
// => [ { name: 'John', age: 19 }, { name: 'Alex', age: 16 } ]
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:
const filteredUsers = users.filter((user) => user.age > 10);
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:
const myFilter = (collection, callback) => {
const result = [];
for (const item of collection) {
// Predicate is used only for checking
// Each element is passed inside the callback in turn
if (callback(item)) {
// The result always adds an item from the original collection
result.push(item);
}
}
return result;
}
const users = [
{ name: 'John', age: 19 },
{ name: 'Richard', age: 1 },
{ name: 'Antony', age: 4 },
{ name: 'Alex', age: 16 },
];
const filteredUsers = myFilter(users, (user) => user.age > 10);
console.log(filteredUsers);
// [
// { name: 'John', age: 19 },
// { name: 'Alex', age: 16 },
// ]
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.