How to use the find() method In Javascript
The find() method returns the value of the first element in an array that satisfies a provided testing function, or undefined if no values satisfy the function.
Syntax:
array.find(callback);
Parameter:
This method accepts the array as the name of the array and a callback denotes the testing function.
Example 1: In this example, The find() method is called on the fruits array and takes a callback function as its argument. The callback function takes each element of the array as its parameter and returns a boolean value indicating whether or not the element matches the desired criteria.
const fruits = ['apple', 'banana', 'orange'];
const result = fruits.find(fruit => fruit === 'banana');
if (result) {
console.log("banana is present in the array");
} else {
console.log("banana is not present in the array");
};
Output
banana is present in the array
Example 2: In this example, we have an array of people containing four objects, each representing a person with a name and an age. We use the find() method to search for the first object in the array that satisfies the provided testing function person => person.age > 30, which checks if the current person’s age is greater than 30.
const people = [
{ name: 'John', age: 28 },
{ name: 'Jane', age: 32 },
{ name: 'Mary', age: 25 },
{ name: 'Mark', age: 36 },
];
// Find the first person in the array
// who is over 30 years old
const result = people.find(person => person.age > 30);
if (result) {
console.log(`The first person over 30 is ${result.name}.`);
} else {
console.log('No people over 30 found in the array.');
};
Output
The first person over 30 is Jane.
Best Way to Find an Item in an Array in JavaScript
In JavaScript, an array is a collection of elements that can hold different data types. There are various ways to check if a specific item is present in an array. In this article, we will see the possible techniques to find the item in a given array in JavaScript.
The most commonly used methods to find if an item is in a JavaScript array are:
Table of Content
- Using the includes() method
- Using the indexOf() method
- Using the find() method
- Using Array.some() method
- Using forEach Loop
- Using the filter() method
Contact Us