Javascript Array Filter Method (with Example)

In this tutorial, you will learn about the javascript array filter() method with the help of multiple examples.

The filter() method creates a new array from the elements of the original array that pass the test defined by the provided function.

Example

const numbers = [2, 5, 8, 12, 4, 6, 3, 7, 15];

//function to find even numbers
function isEven(number) {
    if (number % 2 == 0) {
        return true;
    } else {
        return false;
    }
}
// creates new array
const evenNumbers = numbers.filter(isEven);
console.log(evenNumbers); 
// Output: [ 2, 8, 12, 4, 6 ]

filter() Syntax

The syntax of filter() method is:

arr.filter(callbackFn(currentValue, index, arr), thisArg)

Here, arr is an array.

filter() Parameter

callbackFn: A function to execute on each array element. It returns true if the element passes the test provided in the function, else returns false (Required).

currentValue: Current element being processed in the array (Required).

Index: The index of the current element being processed in the array (Optional).

Index: The index of the current element being processed in the array (Optional).

arr: The array filter() was called upon (Optional).

thisArg: A value to use as this while executing callbackFn. By default, it is undefined (Optional).

filter() Return Value

filter() returns a new array with the elements of the original array that passes the test implemented by the provided function.

Note: filter() method doesn’t change the original array.

Example 1: Filter an Array to only Numbers

const arr = [1, 2, 3, "hello", null, 4, 5, true, 6];
// function to filter numbers
function isNumber(element) {
    return typeof element === 'number';
}
// new array of filtered elements
const numbers = arr.filter(isNumber);
console.log(numbers);


//Using arrow function
const numbers2 = array.filter((element) => typeof element === 'number');
console.log(numbers2);

Output

[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3, 4, 5, 6 ]

In the above example, we have used filter() method to filter out all the non-numeric values and create a new array that contains only numeric values.

Example 2: Find Prime Numbers in the Array

const arr = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
// function to search prime numbers
function isPrime(num) {
    for (let i = 2; num > i; i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return num > 1;
}
// create new array containing prime numbers
const primeNumbers = arr.filter(isPrime);
console.log(primeNumbers);

Output

[ 2, 3, 5, 7, 11, 13 ]

In the above program, we have used filter() method to filter the arr to extract and return prime numbers in a new array.

Example 3: Search an Array

const arr = ["John", "Boris", "Olivia", "Jayden", "Smith"];
//function to filter arr based on a query
function filterItems(arr, query) {
    function condition(element) {
        return element.toLowerCase().includes(query.toLowerCase());
    }
    return arr.filter(condition);
}

console.log(filterItems(arr, "j"));
console.log(filterItems(arr, "bo"));

Output

[ 'John', 'Jayden' ]
[ 'Boris' ]

In the above program, we have used filter() method with include() to search arr based on a query. We have converted the element and query into lowercase using the toLowerCase() method.

include() method is used for checking whether an arr element is matching with the query or not.

Example 4: Filter an Array of Object

const list = [
  { name: 'John', age: 25 },
  { name: 'Smith', age: 20 },
  { name: 'Mike', age: 34 },
  { name: 'David', age: 19 },
  { name: 'Boris', age: 18 }
];

// function to filter list on age
function filterList(person){
    return person.age >= 20;
}
// new array with person age >= 20
const result = list.filter(filterList);
console.log(result);

Output

[ { name: 'John', age: 25 },
{ name: 'Smith', age: 20 },
{ name: 'Mike', age: 34 } ]

In the above program, we have used filter() method to filter the array of objects based on age.

Leave a Comment

Your email address will not be published. Required fields are marked *