How to check if an array includes an object in JavaScript?
Answer: Using some()
and includes()
method
JavaScript offers various built-in methods by which we can check if an array consists of the object or not. Some of the important methods that we are going to discuss in this lesson are given below:
- includes() Method
- some() Method
Using includes()
method
We can check whether the array includes the object or not using the JavaScript includes()
method. This method returns true if an array consists of an object. Otherwise, it returns false. Apart from the JavaScript object, we can check any specific element within the array.
Syntax
array.includes(element, start)
Where,
- the
element
argument represents an element, we are looking/searching for
- the
start
argument represents the index at which the search for the element starts.
Example: Using includes()
method
In the given example, we have used the includes() method to check if an array includes an object or not.
<!DOCTYPE html>
<html>
<head>
<title>Check if an array includes an object</title>
</head>
<body>
<script>
var obj = {"Maths":10, "Science":12}
var arr = ["Maths", "Science", obj];
var result = arr.includes(obj, 0);
console.log(result);
</script>
</body>
</html>
Output
true
Using some()
method
Apart from the includes()
method, we can also check if an array includes an object using or not using some()
method.
This method checks if any of the elements pass a test that is provided as a function. This method executes the function once for each element within the array. This method does not execute the function for the empty array.
The some() method does not change the existing array.
Syntax
array.some(function(currentValue, index, arr), thisValue)
Example: Using some()
method
In this example, we have used the some() method to check whether an array consists of an object or not.
<!DOCTYPE html>
<html>
<head>
<title>Check if an array includes an object</title>
</head>
<body>
<script>
var arr = ["SST", "English", "Hindi",{"Maths":73, "Science":88}];
var result = arr.some(
value => { return typeof value == "object" } );
console.log(result);
</script>
</body>
</html>
Output
true
Conclusion
In this lesson, we have learned how to check if an array consists of an object or not. So we have discussed two methods to check this, firstly we use the includes()
method to check whether an array consists of the object as its element, and then we have used the some()
method.