Searching for JavaScript array.filter example?

In this JavaScript tutorial, We will go through various examples and see the use of array.filter() method in action.

Usage: Array.filter() JavaScript Method

The filter method creates a new array containing all the elements which pass(evaluates to true) the test condition provided in the function.

Note: If no value evaluates to true condition then an empty array is created.

Syntax of Array.filter

JavaScript array.filter syntax is as below-

// arrow function
filter((element) => { ... })
filter((element,index) => { ... })
filter((element,index,array) => { ... })

// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)

// Inline callback function
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
filter(function callbackFn(element, index, array) { ... }, thisArg)

Example 1: Filter a Number Array

Task description -Filter the positive and negative numbers in Javascript using the Array.filter method.


//given array conating both positive & negative numbers
const numbers = [1,-5,2,0,-1,8,-3,10,9,-8]; 

//get the positive numbers in a new array
const positiveNum = numbers.filter(num => num > 0);
console.log(positiveNum);   // show them on console 

//get the negative numbers in a new array
const negativeNum = numbers.filter(num => num < 0);
console.log(negativeNum);   // show them on console 

Example 2: Filter a String Array

Task description- Get all the consonants from an array of alphabets. Use JavaScript Array.filter to complete the task.


//alphabet array
const alphabets = ['a','b','c','d','e','f','g','h','i','j',
                   'k','l','m','n','o','p','q','r','s','t',
                   'u','v','w','x','y','z'];

//get the consonents
const conconents = alphabets.filter(alpha =>
                                   alpha!='a' && alpha!='e' && 
                                   alpha!='i' && alpha!='o' && 
                                   alpha!='u');
//show them on console                                  
console.log(conconents); 

Example 3: Filter an Array of Objects

Task description- Get the detail of the person who can vote, the voting criteria age should be equal to 18 or greater.



//array of objects containg the detail of people
const people= [
  { id: 1, name: "Jack", age: 18 },
  {
    id: 2,
    name: "Jessy",
    age: 20,
  },
  
  {
    id: 3,
    name: "Mark",
    age: 16,
  },

  {
    id: 4,
    name: "Vishal",
    age: 22,
  }
];

//get the array with only who is eligable to vote using JS filter method
const pplCanVote = people.filter((people, index, arr) => {
  return arr[index].age >= 18;
});

//show it on console.
console.log(pplCanVote);

Finally, We hope you understood JavaScript Array.filter example doesn’t forget to follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed