Learn how to use .filter() on Array in javascript

In this post, you will see an example of the array filter() method, .filter() is one of the best methods of Array.

filter() Syntax

Let’s look at the syntax of the .filter method.

arr.filter(callback(item), thisArg)
// arr is an array.

filter() Parameters

The filter() the method takes in:

  • callback – The test function to execute on each array element; returns true if the element passes the test, else false. It takes in:
    • element – The current element being passed from the array.
  • thisArg (optional) – The value to use as this when executing callback.
    By default, it is undefined.

filter() Return Value

Returns a new array with only the elements that passed the test.

  • filter() does not change the original array.
  • filter() does not execute callback for array elements without values.

Example 1: CheckOddNumber

In the following example, we will find odd numbers from the given array of numbers.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// function to check odd numbers
function checkOddNumber(number) {
  if (number % 2 != 0)
    return true;
    return false;

// create a new array by filter odd numbers from the numbers array
let oddNumbers = numbers.filter(checkOddNumber);

// Output: [ 2, 4, 6, 8, 10 ]

Example 2: Filtering out values from Array

const ages = [30, 20, null, "Ten", 45, 60, 90]

function checkAge(element) {
  return element > 30 && !Number.isNaN(element);

let filteredAges = ages.filter(checkAge);
console.log(filteredAges); // [45, 60, 90]

// using arrow function
let anotherFilteredAges = ages.filter((age) => (age > 30 && !Number.isNaN(age)));
console.log(anotherFilteredAges); // [45, 60, 90]

Here, all the ages greater than 30, and all the non-numeric ages are filtered out.

There are a lot we can archive using .filter() method, let’s take a look at another feature of .filter()

Example 3: Search in Array

let countries = ['Pakistan', 'Palestine', 'Denmark', 'Germany', 'Italy', 'Spain', 'India', 'China'];
let query = 'mark'
filteredCountries = countries.filter(element => {
    return element.toLowerCase().indexOf(query.toLowerCase()) !== -1

// output
// ['Denmark']

The element and query both are converted to lowercase, and the indexOf() method is used to check if the query is a present inside element.

That’s it for this time.

Read, try & share.

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk