Skip to main content

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

javascript
const newArray = array.filter((element, index, array) => { return condition; // true -> element stays, false -> excluded });

Callback parameters:

ArgumentDescription
elementThe current array element
indexThe index of the current element
arrayThe original array itself

Example 1. Filtering numbers

javascript
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 is true, includes it in the result.


Example 2. Filtering by an object property

javascript
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

javascript
const values = [0, null, '', 'Hello', undefined, 42]; const truthy = values.filter(Boolean); console.log(truthy); // ['Hello', 42]

Passing Boolean as the function automatically filters out "falsy" values.


Frequent mistakes

  1. Missing return in curly braces:
javascript
const result = arr.filter(num => { num > 5 }); // undefined

Correct:

javascript
const result = arr.filter(num => num > 5); // or const result = arr.filter(num => { return num > 5 });
  1. Trying to change elements inside filter:

filter() is not meant for mutation - only for selection. Use map() for transformations.


When to use filter()

GoalDoes filter() fit
Select elements by a conditionYes
Transform valuesNo - use map()
Find one elementNo - use find()
Change the original arrayNo - 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()

MethodWhat it doesSize of the new array
map()Transforms every elementAlways the same
filter()Selects elements by a conditionCan be smaller

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.