Tuesday, December 13, 2022

JavaScript filter Method With Examples

The JavaScript Array filter() method is used to filter out the elements from the given array that doesn't pass the condition implemented by the provided function and return a new array with the remaining elements.

JavaScript filter method syntax

filter(callbackFunction(element, index, array), thisArg)

Parameters:

  1. callbackFunction- A function to execute for each element in the array. In this function you will write the condition that should return true to keep the element in the resulting array, false otherwise.
    The callback function is called with the following arguments:
    • element- The element in the array being processed currently.
    • index- The index of the current element being processed in the array.
    • array- The array filter() was called upon.
  2. thisArg- This parameter is optional. A value to be used as this when executing callbackFunction.

Filter method returns a new array consisting of the elements that pass the condition of the callback function.

JavaScript filter() examples

1. In an array of cities you want to get cities having length > 7.

const cities = ['Mumbai', 'Bengaluru', 'London', 'Beijing', 'Charlotte'];

function checkCity(city){
  return city.length > 7;
}
const newCities = cities.filter(checkCity);
console.log(newCities); //  ['Bengaluru', 'Charlotte']
Callback function can also be written as an arrow function to make code more concise and readable.
const cities = ['Mumbai', 'Bengaluru', 'London', 'Beijing', 'Charlotte'];
const newCities = cities.filter(city => city.length > 7);
console.log(newCities);

2. To get the even numbers in an array of numbers.

const numbers = [2, 5, 10, 13, 24, 56, 68, 75];
const evenNum = numbers.filter(num => num%2 == 0);
console.log(evenNum); // [2, 10, 24, 56, 68]

3. In an array of Person objects filter out all persons having age < 18

const persons = [{id:1, name:"Ajay", age:9}, 
                  {id:2, name:"Rajiv", age:22}, 
                  {id:3, name:"Bosco", age:25},
                  {id:4, name:"Albert", age:3}];

const personArr = persons.filter(p => p.age > 18);
console.log(personArr); 

//Output
{id: 2, name: 'Rajiv', age: 22}
{id: 3, name: 'Bosco', age: 25}

That's all for this topic JavaScript filter Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array and Object Destructuring
  2. JavaScript Rest Parameter
  3. JavaScript Array slice() method With Examples
  4. React Declarative Approach

You may also like-

  1. BigInteger in Java With Examples
  2. What is Client Side Routing in Angular
  3. HashMap in Java With Examples
  4. Bean Definition Inheritance in Spring

No comments:

Post a Comment