A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Check If an Array Includes an Object in JavaScript
Q:

How to Check If an Array Includes an Object in JavaScript

0

How to Check If an Array Includes an Object in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JavaScript some() Method

You can use the JavaScript some() method to find out if a JavaScript array contains an object.

This method tests whether at least one element in the array passes the test implemented by the provided function. Here's an example that demonstrates how it works:

<script>
// An array of objects
var persons = [{name: "Harry"}, {name: "Alice"}, {name: "Peter"}];

// Find if the array contains an object by comparing the property value
if(persons.some(person => person.name === "Peter")){
    alert("Object found inside the array.");
} else{
    alert("Object not found.");
}
</script

Note that if try to find the object inside an array using the indexOf() method like persons.indexOf({name: "Harry"}) it will not work (always return -1). Because, two distinct objects are not equal even if they look the same (i.e. have the same properties and values). Likewise, two distinct arrays are not equal even if they have the same values in the same order.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now