In JavaScript, find methods is used to search for elements in an array based on a given condition.
KeyPoints:
1. The find method returns the value of the first element in the array that satisfies the provided testing function.
2. It returns the first element that matches the condition. If no elements match, it returns undefined.
Example:
1. Filtering Even Numbers:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const data = numbers.find(num => num % 2 === 0);
console.log(data); // Output: 2
2. Filtering string from the array
const fruits = ['Apple', 'Banana', 'Orange'];
const filteredData= fruits.find(fruit => fruit== 'Orange');
console.log(filteredData); // Output: Orange
3. 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.find(employee => employee.age > 36);
console.log(data); // Output: { name: 'John', age: 38 }
find() method – Interview Questions
Q 1: What does find() do?
Ans: Returns the first matching element.
Q 2: Does it return an array?
Ans: No, returns element.
Q 3: Does it stop after the match?
Ans: Yes.
Q 4: If no match is found?
Ans: Returns undefined.
Q 5: Use case?
Ans: Finding a single record.
find() method– Objective Questions (MCQs)
Q1. The find() method returns ______.
Q2. If no element matches, find() returns ______.
Q3. find() stops searching after ______.
Q4. Which method returns index instead of value?
Q5. find() works on ______.