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 } ]

filter() method – Interview Questions

Q 1: What does filter() do?
Ans: Filters array elements.
Q 2: Does it return new array?
Ans: Yes.
Q 3: Does it modify original array?
Ans: No.
Q 4: Callback returns?
Ans: Boolean.
Q 5: Use case?
Ans: Searching data.

filter() method – Objective Questions (MCQs)

Q1. The filter() method is used to ______.






Q2. filter() works on which data type?






Q3. The callback function in filter() must return ______.






Q4. Does filter() change the original array?






Q5. Which value will be included by filter()?