Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Using `.includes` to find if an array of objects contains a specific object

I am a bit new to javascript ES6, and I am having difficulty understanding why the below is not functioning as expected:

let check = [{name: 'trent'},{name: 'jason'}].includes({name: 'trent'}); 
// expect true - returns false

Thanks!

like image 272
Trent R Avatar asked Mar 09 '18 06:03

Trent R


People also ask

How do you check if an array contains a specific item?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

How do you check if an array contains a specific value in JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.


2 Answers

One of these

let check = [{name: 'trent'}, {name: 'jason'}]
  .map(item => item.name)
  .includes('trent');

OR

let check = !![{name: 'trent'}, {name: 'jason'}].find(({name})=> name ==='trent')
like image 58
sultan Avatar answered Oct 22 '22 16:10

sultan


includes essentially checks if any element === the element you're searching for. In case of objects, === means literally the same object, as in the same reference (same place in memory), not the same shape.

var a1 = { name: 'a' }
var a2 = { name: 'a' }

console.log(a1 === a2) // false because they are not the same object in memory even if they have the same data

But if you search for an object that is actually in the array it works:

var a1 = { name: 'a' }
var a2 = { name: 'a' }
var array = [a1, a2]

console.log(array.includes(a1)) // true because the object pointed to by a1 is included in this array 
like image 24
nem035 Avatar answered Oct 22 '22 14:10

nem035