I'm attempting to find an object in an array using Array.prototype.includes
. Is this possible? I realize there is a difference between shallow and deep comparison. Is that the reason the below code returns false? I could not find a relevant answer for Array.includes()
.
includes() The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
Array.includes
compares by object identity just like obj === obj2
, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some()
instead which takes a function:
const arr = [{a: 'b'}] console.log(arr.some(item => item.a === 'b'))
But of course you then need to write a small function that defines what you mean by equality.
Its' because both of the objects are not the same. Both are stored at different place in memory and the equality operation results false
.
But if you search for the same object, then it will return true
.
Also, have a look at the below code, where you can understand that two identical objects also results false
with the ===
operator.
For two objects to return true
in ===
, they should be pointing to same memory location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With