3

Javascript does not allow comparision of arrays using includes ?

See this example:

let x = [[1,2], [3,4]]
let y = x[0]
let z = [1,2]

console.log(y,z)
// Output: [ 1, 2 ] [ 1, 2 ]
console.log(x.includes(y), x.includes(z))
// Output: true false 

I would like to have x.includes(z) to be true.

I was made aware of the qurestion check-if-an-array-contains-any-element-of-another-array-in-javascript by the comments, but it does not answer my question as I want to check if the array has exactly the same elements using includes not only some.

Moreover, this question how-to-compare-arrays-in-javascript does not explain why includes does not work. It tells how to do it, which is not the point of my question.

zeh
  • 1,197
  • 2
  • 14
  • 29
  • 2
    Because they reference to different memory locations – AlexOwl Mar 14 '19 at 11:05
  • You can't check arrays directly like that – Wimanicesir Mar 14 '19 at 11:05
  • You could use `JSON.stringify(x).includes(JSON.stringify(z))` which is true – Luca Kiebel Mar 14 '19 at 11:06
  • There *has* to be a good dupetarget for this... (And adiga found it.) – T.J. Crowder Mar 14 '19 at 11:07
  • I don't want to see if two arrays are equal, like explained in the refered question. That answer question (that I was aware of) did not help me. – zeh Mar 14 '19 at 11:32
  • No? Think carefully, how `includes` works, maybe the duped post opens to you too ... – Teemu Mar 14 '19 at 11:48
  • 1
    Looking back, now that I know the answer, the key thing was the fact that in JS the equaliry signs (==) compares addresses in the memory, and `includes` uses == under the hood. The question marked as duplicate has reference to memory only twice and only after the 5th answer or so. Also, one could think it is naive to think that == should behave diferently, but in python, for example, an array (or list) has the == implemented as I was expecting, but clearly in JS it is not, hence the confusion. – zeh Mar 14 '19 at 11:58

2 Answers2

5

Because [1, 2] === [1, 2] is false. Different arrays are not equal to each other, not even if they have the same contents. (This is true of all objects.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

You can use includes for the values of the array when they are "primitive types", but not with a whole array.

When you use includes, it checks if the current element of the array is === to the element that is passed as an argument.

In your case, it would be checking if [1,2] === [1,2] this yields false, and it's because via the === comparator you are just checking for the memory reference when applied to arrays.

If you want to do something like comparing for if the whole array is the same probably you are better of using a function like _. isEqual from lodash or implementing your own comparator function.

Alejandro Vales
  • 2,816
  • 22
  • 41