How to use Array.prototype.find Method In Javascript
Another approach to check if an array includes an object in JavaScript is by using the find method. This method iterates over the array and returns the first element that satisfies the provided testing function. If no elements satisfy the testing function, it returns undefined.
Example: In this example, we will use the find method to check if the array includes the specified object.
let obj = { "geeks1": 10, "geeks2": 12 };
let arr = ["geeks1", "geeks2", "geeks3", obj];
// Use JavaScript find() method
let found = arr.find(element => element === obj);
if (found !== undefined) {
console.log("Object found in the array");
} else {
console.log("Object not found in the array");
}
Output
Object found in the array
How to check if an array includes an object in JavaScript ?
In JavaScript, an array acts like like list. It’s a way to group multiple items together under one name. You can store different things in your list, like numbers, words, or even other lists. Each item in the list has its own place, and you can access it using a number called its “index.”
We will check if an array includes an object or not in JavaScript. There are various methods to check whether an array includes an object or not.
These are the following approaches by using these we can check if an array includes an object in JavaScript:
Table of Content
- Using includes() Method
- Using some() Method
- Using filter() Method
- Using findIndex() Method
- Using Lodash _.find() Method
- Using the spread operator (…) and Math.floor():
- Using Array.prototype.find Method