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?
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?
Share Improve this question edited Jan 4, 2018 at 4:47 Tomalak 338k68 gold badges546 silver badges635 bronze badges asked Jan 4, 2018 at 4:24 katuskatus 6691 gold badge8 silver badges16 bronze badges 2 |5 Answers
Reset to default 13includes
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).
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
.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/[email protected]/lodash.min.js"></script>
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
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'
[1,2,3] !== [1,2,3]
. – Bergi Commented Jan 4, 2018 at 10:32