Filter in an array
The filter() method is one of the most useful array methods in JavaScript.
It is used to filter elements by a certain condition, creating a new array only from the elements for which the condition returned true.
Syntax
const newArray = array.filter((element, index, array) => {
return condition; // true -> element stays, false -> excluded
});Callback parameters:
| Argument | Description |
|---|---|
element | The current array element |
index | The index of the current element |
array | The original array itself |
Example 1. Filtering numbers
const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6] - the original array did not change
filter()checks every element, and if the condition istrue, includes it in the result.
Example 2. Filtering by an object property
const users = [
{ name: 'Tim', age: 25 },
{ name: 'Alex', age: 17 },
{ name: 'John', age: 30 }
];
const adults = users.filter(user => user.age >= 18);
console.log(adults);
// [
// { name: 'Tim', age: 25 },
// { name: 'John', age: 30 }
// ]A common scenario - selecting users, products, records and so on by a condition.
Example 3. Removing "empty" values
const values = [0, null, '', 'Hello', undefined, 42];
const truthy = values.filter(Boolean);
console.log(truthy); // ['Hello', 42]Passing
Booleanas the function automatically filters out "falsy" values.
Frequent mistakes
- Missing
returnin curly braces:
const result = arr.filter(num => { num > 5 }); // undefinedCorrect:
const result = arr.filter(num => num > 5);
// or
const result = arr.filter(num => { return num > 5 });- Trying to change elements inside
filter:
filter()is not meant for mutation - only for selection. Usemap()for transformations.
When to use filter()
| Goal | Does filter() fit |
|---|---|
| Select elements by a condition | Yes |
| Transform values | No - use map() |
| Find one element | No - use find() |
| Change the original array | No - filter returns a new array |
In short:
filter()returns a new array with the elements that passed the check.
Memorization formula:
arr.filter(condition) -> new_subset_array.
Difference between map() and filter()
| Method | What it does | Size of the new array |
|---|---|---|
| map() | Transforms every element | Always the same |
| filter() | Selects elements by a condition | Can be smaller |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.