13

Why does the following line return false in Javascript:

 [[1,2,3], [1,2,4]].includes([1,2,3]);

What is the underlying logic behind that?

Tomalak
  • 332,285
  • 67
  • 532
  • 628
katus
  • 649
  • 1
  • 6
  • 16
  • 2
    It's because [`[1,2,3] !== [1,2,3]`](https://stackoverflow.com/q/7837456/1048572). – Bergi Jan 04 '18 at 10:32
  • Related: [IndexOf array of several arrays with javascript](https://stackoverflow.com/q/45210694/1048572) – Bergi Jan 04 '18 at 10:32

5 Answers5

13

includes compares using SameValueZero equality algorithm. (As mentioned in developer.mozilla.org). When searching for objects (array is object as well), it will match only references to the same object.

Additionally, Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same. The equality operator will only test if two object are actually exactly the same instance (e.g. myObjVariable==myObjVariable, works for null and undefined too).

Duc Filan
  • 6,769
  • 3
  • 21
  • 26
3

Both [1,2,3] expressions create a new array object. Even though the contents are the same, the objects themselves are different.

See for example this:

const array1 = [1, 2, 3];
const array2 = [1, 2, 3];

console.log(array1 == array2); // false, different objects

const array = [1, 2, 3];

console.log(array == array); // true, same object
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

.includes check the equity for every value in the array. In JavaScript, two arrays with the same values are not equivalent. See this thread for more details: How to compare arrays in JavaScript?

You could do this to check if an array contains an array. I use Lodash for the equity comparison and the .some property to check if one element in the array returns true.

console.log(
  [[1,2,3], [1,2,4]].some((array) => _.isEqual(array, [1,2,3]))
)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
0

Because they are mutable. If you want to check for array, you need to check by variable.

var a = [1,2];
var b = a;
 [a].includes(b);

When you check for [[1,2,]].includes([1,2,3]), it returns false, because they are treated as two different objects; i.e. [1,2] == [1,2] returns false.

However, for immutable objects, such as string and number, you can check directly, such as

["a", "b"].includes("a")  //true
[1, 2].includes(1) //true
"a" == "a"   // true
orabis
  • 2,749
  • 2
  • 13
  • 29
0

You can do it using only Array.some() (Array.prototype.some() more precisely) method like the followings

console.log([[1,2,3], [1,2,4]].some(e => e[0] === 1 && e[1] === 2 && e[2] === 3)); // would return 'true'
console.log([[1,2,3], [1,2,4]].some(e => e[0] === 1 && e[1] === 2 && e[2] === 4)); // would return 'true'
console.log([[1,2,3], [1,2,4]].some(e => e[0] === 1 && e[1] === 2 && e[2] === 5)); // would return 'false'
Sangmoon Oh
  • 81
  • 1
  • 2