filter() Method
The filter(callback)
method is used for one operation only – array filtering,
that is, when more than one element from a collection should be selected using a
specific criterion.
array.filter((element, index, array) => {
// Callback body
});
- Does not change the original array.
- Iterates over the original array element by element.
- Returns a new array.
- Adds elements to the returned array that satisfy the callback condition.
- If the callback returns
true
, the element is added to the returned array. - If the callback returns
false
, the item is not added to the returned array. - If none of the elements satisfies the condition, it returns an empty array.
const values = [51, -3, 27, 21, -68, 42, -37];
const positiveValues = values.filter(value => value >= 0);
console.log(positiveValues); // [51, 27, 21, 42]
const negativeValues = values.filter(value => value < 0);
console.log(negativeValues); // [-3, -68, -37]
const bigValues = values.filter(value => value > 1000);
console.log(bigValues); // []
// The original array has not changed
console.log(values); // [51, -3, 27, 21, -68, 42, -37]
That is, the filter
method calls a callback function for each element of the
original array, and if its result is true
, the current element is added to the
new array.
Filtering unique elements
Using the filter()
method, you can filter any array so that only unique
elements remain. This technique only works with an array of primitive values,
not objects.
Let's go back to the group of students and the array of all attended subjects
generated with the flatMap()
method.
const students = [
{ name: "Mango", courses: ["mathematics", "physics"] },
{ name: "Poly", courses: ["informatics", "mathematics"] },
{ name: "Kiwi", courses: ["physics", "biology"] },
];
const allCourses = students.flatMap(student => student.courses);
// ['mathematics', 'physics', 'informatics', 'mathematics', 'physics', 'biology']
The variable allCourses
stores an array of all attended subjects that can be
repeated. The task is to create a new array containing only unique subjects,
that is, without repetitions.
const uniqueCourses = allCourses.filter(
(course, index, array) => array.indexOf(course) === index
);
Using array.indexOf(course)
, search for the first match of the current
course
element and get its index in the original array of all courses. The
index
parameter stores the index of the current course
element when
iterating over the array with the filter
method.
If the result of indexOf()
and the value of index
are equal, this is a
unique element, because this is the first time such a value is found in the
array, and the filter handles it in the current iteration.
# Array of all courses
['mathematics', 'physics', 'informatics', 'mathematics', 'physics', 'biology']
For the 'mathematics'
element with index 0:
indexOf()
will return 0 because it looks for the first match.- The
index
parameter value will be 0. - They are equal, so this is a unique element.
For the 'mathematics'
element with index 3:
indexOf()
will return 0 because it looks for the first match.- The
index
parameter value will be 3. - They are not equal, so this is a repetition, not a unique element.
Array of objects
When working with an array of objects, filtering is done by a certain property value. The result is a new array of filtered objects.
For example, there is an array of students with test scores. It is necessary to filter out the best (scores above 80), worst (scores below 50) and average students (scores from 50 to 80).
const LOW_SCORE = 50;
const HIGH_SCORE = 80;
const students = [
{ name: "Mango", score: 83 },
{ name: "Poly", score: 59 },
{ name: "Ajax", score: 37 },
{ name: "Kiwi", score: 94 },
{ name: "Houston", score: 64 },
];
const best = students.filter(student => student.score >= HIGH_SCORE);
console.log(best); // Array of objects named Mango and Kiwi
const worst = students.filter(student => student.score < LOW_SCORE);
console.log(worst); // Array with one Ajax object
// In a callback function, it is convenient to destructure the properties of an object
const average = students.filter(
({ score }) => score >= LOW_SCORE && score < HIGH_SCORE
);
console.log(average); // Array of objects named Poly and Houston