filter() method

In JavaScript, filter is an array method used to search for elements in an array based on a given condition.

Key Points

1. The filter method creates a new array containing all elements that pass the test implemented by the provided function.

2. It returns an array of all elements that satisfy the condition. If no elements match the condition, it returns an empty array.

Example:

1. Filtering Even Numbers:


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

2. Filtering Odd Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(evenNumbers); // Output: [1, 3, 5, 7]

3. Filtering string from the array


const fruits = ['Apple', 'Banana', 'Orange'];
const filteredData= fruits.filter(fruit => fruit== 'Orange');
console.log(filteredData); // Output: ['Orange']

4. Filtering Objects in an Array


const employees = [
  { name: 'John', age: 38 },
  { name: 'Tom', age: 37 },
  { name: 'Mathew', age: 35 },
  { name: 'Andrew', age: 30 },
];

const data = employees.filter(employee => employee.age > 36);
console.log(data); // Output: [ { name: 'John', age: 38 }, { name: 'Tom', age: 37 } ]