JavaScript
Filtering with filter
Learn to select elements matching a condition with filter.
Filtering with filter
The filter method walks the array with a predicate function and builds a new array from every element for which the predicate returns true. Elements that fail the test are dropped.
The result is always an array, but its length may be smaller than the original, even zero. The original array is again left untouched. If you want to list only the products in stock at a shop, filter is your friend.
filter can return an empty array
If no element passes the test, filter returns an empty array; it never throws. This quiet behaviour can be surprising.
For example, if you filter ages greater than 100 and nobody qualifies, you get []. That is why checking the result's length helps you show a 'no records' message in the interface. An empty array is still a valid array.
Exercise Filter passing scores
From the scores array, select the ones that are 50 or higher and store them as passing. Print the result.
Show example solution
const scores = [35, 72, 50, 48, 90];
// filter scores 50 or higher
const passing = scores.filter(score => score >= 50);
console.log(passing);
Exercise Filter long names
From the names array, keep names whose length is 5 or more and store them as longNames. Print the result.
Show example solution
const names = ["Ed", "Zeynep", "Ali", "Memet"];
// keep names with length 5 or more
const longNames = names.filter(name => name.length >= 5);
console.log(longNames);
Test yourself
-
What is the result of const evens = [1,2,3,4].filter(n => n % 2 === 0);?
const evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
Show answer
[2, 4] — Correct. filter keeps 2 and 4, which pass the test, returning [2, 4].
-
keep only positive numbers
const nums = [-3, 5, -1, 8];
const positives = nums.filter(n => ____);
console.log(positives);
Show answer
const nums = [-3, 5, -1, 8];
const positives = nums.filter(n => n > 0);
console.log(positives);
-
Match each method to its purpose
- map
- transforms every element
- filter
- keeps matching elements
- forEach
- walks each element
- includes
- checks if element exists
Next lesson: Finding with find