0
0
Javascriptprogramming~5 mins

Filter method in Javascript

Choose your learning style9 modes available
Introduction

The filter method helps you pick only the items you want from a list. It makes a new list with just those items.

When you want to find all even numbers from a list of numbers.
When you want to get all names that start with a certain letter.
When you want to remove unwanted items from a list, like expired products.
When you want to find all users who are active in a list of users.
Syntax
Javascript
array.filter(function(element) {
  return condition;
});

The filter method creates a new array with all elements that pass the test in the function.

The function inside filter should return true to keep the element, or false to skip it.

Examples
This keeps only even numbers from the list.
Javascript
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
This keeps names that start with 'A'.
Javascript
const names = ['Anna', 'Bob', 'Alice', 'Brian'];
const aNames = names.filter(name => name.startsWith('A'));
This keeps only products that are not expired.
Javascript
const products = [
  {name: 'Milk', expired: false},
  {name: 'Cheese', expired: true}
];
const fresh = products.filter(product => !product.expired);
Sample Program

This program keeps numbers greater than 18 from the list and prints them.

Javascript
const numbers = [10, 15, 20, 25, 30];
const filtered = numbers.filter(num => num > 18);
console.log(filtered);
OutputSuccess
Important Notes

The original array does not change when you use filter.

If no elements pass the test, filter returns an empty array.

You can use filter with any condition you want, making it very flexible.

Summary

Filter helps you create a new list with only the items you want.

It uses a function that returns true or false for each item.

The original list stays the same after filtering.