Why Array.includes() Fails With Nested Arrays
If you try to check if a nested array exists in an array of arrays, you’ll get an unexpected result:
const matrix = [[1,2], [2,3]];
console.log(matrix.includes([1,2])); // false You’d expect true, but JavaScript returns false. Here’s why.
The Problem: Reference vs. Value
JavaScript compares arrays by reference (memory location), not by value (contents). Even though [1,2] looks identical, it’s a different object in memory:
[1,2] === [1,2] // false, different objects! So includes() can’t find a match because it’s looking for the exact same object, not one with the same contents.
Solution: Using some()
Use some() with a comparison function to check array contents:
const matrix = [[1,2], [2,3]];
const target = [1,2];
const found = matrix.some(arr =>
JSON.stringify(arr) === JSON.stringify(target)
);
console.log(found); // true This converts both arrays to strings for comparison, effectively checking their contents.
Limitations of JSON.stringify
- Order-sensitive:
[1,2]and[2,1]are different. - Non-serializable values: functions,
undefined, andSymbolare lost or omitted. - Circular references: will throw an error.
- Type coercion:
JSON.stringify([1, "1"])vs other subtle differences.