Onjsdev

Share


JavaScript Filter() Method


By onjsdev

Mar 3rd, 2024

Javascript filter() is an array method that allows us to create a new array from an existing one by filtering out elements that meet conditions provided by a callback function.

It is especially very useful when we want to obtain a new array by removing unwanted elements.

Let's see how it works.

How Does the Javascript filter Method Work?

The Javascript filter method iterates through an array, and if the callback function returns true for the element being processed in the iteration, that element is added to the filtered array.

Here's a basic example:

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter(function(number) {
  return number % 2 === 0;
});

console.log(evenNumbers); // Output: [2, 4]

In this example, the filter method is used to obtain even numbers. The callback function checks if each number is even (divisible by 2). If it is, the number is added to the evenNumbers array.

Callback Function

The callback function passed to the filter method as a parameter is where you define the condition for filtering elements.

It receives three arguments:

  • element: The current element being processed in the array.
  • index (optional): The index of the current element.
  • array (optional): The array on which filter was called.

And, a callback function can be defined in different ways:

Using Named Function

function isEven(number,index) {
  return number % 2 === 0;
}

const numbers = [1, 2, 3, 4, 5, 6];
const filteredNumbers = numbers.filter(isEven);

Using Arrow Function

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]

Filter Method With Array of Objects

You can use the filter method in javascript with array of objects. For example, let's say you have an array including some objects representing people and you want to create a new array containing only people who are over the age of 18. You could use the filter method like this:

const people = [
  { name: 'John', age: 20 },
  { name: 'Jane', age: 17 },
  { name: 'Bob', age: 25 },
  { name: 'Mary', age: 16 }
];

const adults = people.filter(function(person) {
  return person.age >= 18;
});
console.log(adults);
/*

[
  { name: 'John', age: 20 },
  { name: 'Bob', age: 25 }
]

*/

Conclusion

In this article we have discussed the js filter method with examples. If you want to learn more about array methods in javascript you can check the following articles:

Thank you for reading