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!
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.
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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With