In this post, we will see if array contains string or object in given array
Using IndexOf Method:
let arr = [{id: 1, name: "Jayaram"}, {id: 2, name: "Javasavvy"}, {id: 3, name: "Vijay"}];
let obj = {id: 2, name: "Jayaram"};
// Using indexOf
if (arr.indexOf(obj) !== -1) {
console.log("Object found in array!");
} else {
console.log("Object not found in array.");
}
// Using includes (modern browsers)
if (arr.includes(obj)) {
console.log("Object found in array!");
} else {
console.log("Object not found in array.");
}
Using Includes Method:
The find()
method returns the first element in the array that satisfies the provided testing function. If no elements pass the test, it returns undefined
let arr = [{id: 1, name: "Jayaram"}, {id: 2, name: "Javasavvy"}, {id: 3, name: "Vijay"}];
let obj = {id: 2, name: "Jayaram"};
// Using includes (modern browsers)
if (arr.includes(obj)) {
console.log("Object found in array!");
} else {
console.log("Object not found in array.");
}
Using ES6 Array.Find Method:
let arr = [{id: 1, name: "Jayaram"}, {id: 2, name: "Javasavvy"}, {id: 3, name: "Vijay"}];
let obj = {id: 2, name: "Jayaram"};
let found = arr.find(element => element.id === obj.id && element.name === obj.name);
if (found) {
console.log("Object found in array!");
} else {
console.log("Object not found in array.");
}
Using Brute force Approach method to Iterate over loop:
Note that the indexOf()
method and the includes()
method use strict equality (===
) to compare the elements in the array, so the objects must have the same properties and values in the same order for the method to return a positive result.
If you want to check if an object with a specific property value is in the array, you can use a for
loop and compare the properties:
let arr = [{id: 1, name: "Jayaram"}, {id: 2, name: "Javasavvy"}, {id: 3, name: "Vijay"}];
let id = 2;
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
console.log("Object found in array!");
break;
}