70

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 tools console

E_net4
  • 27,810
  • 13
  • 101
  • 139
timothym
  • 2,853
  • 5
  • 19
  • 26
  • 1
    because `{a: 'b'} == {a: 'b'}` is `false`? – Federkun Jul 30 '18 at 23:18
  • 2
    Yes, you can use Array.prototype.includes to find an object in an array, but it must be the exact same object, not a newly created object like your screenshot shows. This works: `const a = {}; console.log( [a].includes( a ) );`. – Paul Jul 30 '18 at 23:19

8 Answers8

114

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.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Mark
  • 90,562
  • 7
  • 108
  • 148
  • If my object is like {a: 'b',b:'c'}, how I'm supposed to compare to be sure it's the same object? Some function tests whether at least one element in the array passes the test... – probitaille Jul 17 '20 at 12:58
  • @probitaille, you need a function that compares objects the way you want, then use that for the comparison instead of `==`. There options for that here: https://stackoverflow.com/questions/1068834/object-comparison-in-javascript – Mark Jul 17 '20 at 15:00
  • `Array#includes` actually uses the same-value-zero equality algorithm. – Unmitigated May 02 '21 at 00:06
  • Interesting @iota. Are there any examples where `a === b` and same-value-zero equality are different in this context (other than maybe NaN)? – Mark May 02 '21 at 00:47
9

Its' because both of the objects are not the same. Both are stored at different place in memory and the equality operation results false.

But if you search for the same object, then it will return true.

enter image description here

Also, have a look at the below code, where you can understand that two identical objects also results false with the === operator.

For two objects to return true in ===, they should be pointing to same memory location.

enter image description here

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Rahul Gandhi
  • 1,035
  • 1
  • 11
  • 24
4

This is because the includes checks to see if the object is in the array, which it in fact is not:

> {a: 'b'} === {a: 'b'}
false

This is because the test for equality is not testing if the objects are the same, but whether the point to the same object. Which they don't.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
4

You are on the right track but, the issue is the difference between reference and value types, you currently are using a reference type (object literal), so when you compare what is in the array with what you have, it will compare the references and not the values. this is what I mean:

    var ar = [];
    var x = {a: "b", c: "d" };
    ar.push(x);

    // this will log true because its the same reference
    console.log("should be true: ", ar[0] === x);

    ar.push({a: "b", c: "d" });
    // this will log false because i have created 
    // a different reference for a new object.
    console.log("should be false: ", ar[1] === x);
    
    // Think of it like this
    var obja = { foo: "bar" }; // new reference to 'obja'
    var objb = { foo: "bar" }; // new reference to 'objb'
    var valuea = 23;
    var valueb = 23;
    
    // 'obja' and 'obja' are different references
    // although they contain same property & value
    // so a test for equality will return false
    console.log("should be false: ", obja === objb);

    // on the other hand 'valuea' and 'valueb' are 
    // both value types, so an equality test will be true
    console.log("should be true: ", valuea === valueb);

to achieve what you want, you either have to have added the actual reference, as I did above, or loop through the array and compare by unique property of the objects.

Ebi Igweze
  • 460
  • 3
  • 8
4

you can use find to returns the value of the this element

const array = [{a: 'b'}];
array.includes(array.find(el=>el.a==='b'));
Bourja Hamid
  • 93
  • 1
  • 7
3

const arr = [{a: 'b',b:'c'},{a: 'c'}]
console.log(arr.some(item => item.b === 'c'))
  • 2
    Can you please elaborate whats different in your solution and how it differs from other answers or how is it better. – sarmahdi Dec 18 '19 at 04:33
2

Yes, you can, if only so

const arr = [{a:'a'},{a: 'b'}]
const serch = arr[1]
console.log(arr.includes(serch))
BuGaGa
  • 302
  • 2
  • 9
0

You cannot use string comparisons on objects unless you first convert them to strings with...

JSON.stringify(TheObject)

So to loop through all objects in an array so as to prevent adding a duplicate object, you can use something like this...

let Bad=false;

ObjectArray.forEach(function(e){if(JSON.stringify(NewObject)===JSON.stringify(e)){Bad=true;}});

if(Bad){alert('This object already exists!');} else {ObjectArray.push(NewObject);}