Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 672
Rey Avatar asked Dec 14 '22 13:12

Rey


2 Answers

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))
like image 82
Lazar Ljubenović Avatar answered May 11 '23 00:05

Lazar Ljubenović


In that case you could use some method instead and it will return true on first match.

let array = [{"name" : "John", age: 24}, {"name" : "Jane", age: 36}]
let check = array.some(({name}) => name == 'Jane');
console.log(check)
like image 33
Nenad Vracar Avatar answered May 11 '23 00:05

Nenad Vracar