Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.includes() to find object in array

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().

dev tools console

like image 482
timothym Avatar asked Jul 30 '18 23:07

timothym


People also ask

What is the function of the includes () in arrays?

includes() The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

How do you find the object of an array of objects?

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.


2 Answers

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.

like image 79
Mark Avatar answered Oct 05 '22 20:10

Mark


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.

enter image description here

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.

enter image description here

like image 30
Rahul Gandhi Avatar answered Oct 05 '22 21:10

Rahul Gandhi