Using Array.prototype.includes to target property in an array of objects

  • A+
Category:Languages

With Array.prototype.includes you can do something like this:

let array1 = [1, 2, 3];  console.log(array1.includes(2)); // return true 

My question is: can you use includes for an array of objects, where you want to find, say, "name" = "Jane"? Take for instance the following data:

let array2 = [{"name" : "John", age: 24}, {"name" : "Jane", age: 36}]

Is this something you can do with the includes method - and what would it look like?

 


You can use it, but only if you have the reference to the object (not its structural equivalent).

const o1 = { name: '1' } const o2 = { name: '2' } const arr = [o1, o2] arr.includes(o1) // true arr.includes({ name: '1' }) // false 

This is because includes uses the "SameValueZero" algorithm, as per the spec (emphasis mine):

includes compares searchElement to the elements of the array, in ascending order, using the SameValueZero algorithm, and if found at any position, returns true; otherwise, false is returned.

"SameValueZero" will always return false for different references, hence the second attempt from the code above will return false.

You can use Array#some instead, which lets you specify a lambda as the parameter. Then you can write your custom equality logic even for objects.

arr.some(o => o.name == '1') // true 

From your comment, I see you're interested in checking against multiple values. You can simply use the || operator with some in this case:

arr.some(o => o.name == '1' || o.name == '2' || o.name == '3') 

If you do not wish to specify all of them like this, you can do something like the following.

arr.some(o => ['1', '2', '3'].includes(o.name)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: