Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  126] [ 1]  / answers: 1 / hits: 99313  / 6 Years ago, mon, july 30, 2018, 12:00:00

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


More From » arrays

 Answers
156

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.


[#53847] Thursday, July 26, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronaldodarioc

Total Points: 441
Total Questions: 105
Total Answers: 106

Location: Christmas Island
Member since Sun, Mar 7, 2021
3 Years ago
;