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:
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).
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 },
// ]
The Hexlet support team or other students will answer you.
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.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.