0

I got an array A and the console shows me:

Array [ Object, Object ].

When I click on one of the Object elements, the properties are shown on the console.

Now, I got a variable B which contains the first Object of my array A. I want to check this using the includes function:

A.includes(B)

However, it returns false. Is there something wrong with the use of includes()?

altocumulus
  • 21,179
  • 13
  • 61
  • 84
Derick Kolln
  • 633
  • 7
  • 17
  • 2
    Probably it does *not* contain the same object then. Notice that an equally-looking object is not enough. – Bergi Aug 04 '17 at 15:00

2 Answers2

3

If I understand your question correctly, your setup looks like this:

const A = [ {hello: "world"}, {hi: "everyone"} ];
const B = {hello: "world"};
console.log(A.includes(B)); // returns false

A.includes(B) returns false because Javascript evaluates object equality based on objects' references (where they are stored in memory), not their values. As a result, even though B looks like it is included in A, the two objects have different references because they are declared independently of each other. You can read more about object equality in Javascript here: http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html

Using this information, you can change your setup so you get the expected answer:

const A = [ {hello: "world"}, {hi: "everyone"} ];
const B = A[0];
console.log(A.includes(B)); // returns true
Asher Dale
  • 149
  • 1
  • 11
2

This works fine for me, but you might be getting hung up on the fact that includes works by strict equality. An object is not considered equal to another object with the same properties unless that other object is actually the same object. See the following example:

const b = {} //some object
const A = [b, 2]
console.log(A.includes(b)) //true
console.log([{}, 2].includes(b)) //false because {} !== b
csander
  • 1,385
  • 10
  • 11