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;
  else
    return false;
}

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

// 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 a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.