5

const myArray = [
  [2, 4], "cat", "hamster", 9
]
console.log(myArray.includes("cat"))
console.log(myArray.includes([2, 4]))

output is true, false. does includes() not work for arrays inside of arrays? thanks

3
  • 7
    Because [2, 4] inside myArray and [2, 4] passed to includes() method are two different arrays - they are different objects in memory Commented Jun 14, 2022 at 17:57
  • 4
    Two different arrays are still different even if they contain the same values. You'd have to compare them differently. Commented Jun 14, 2022 at 17:58
  • Objects, including arrays, are compared by identity, not by their contents. Commented Jun 14, 2022 at 18:09

2 Answers 2

3

Because Array in js is a specific object, the [2,4] inside myArray is object and [2,4] that you switch to includes is anther object. If you want that includes return true you must do this:

var array = [2, 4]

const myArray = [array, "cat", "hamster", 9]

console.log(myArray.includes(array))
Sign up to request clarification or add additional context in comments.

Comments

3

A string is a value type, so a comparison between two strings will compare the value of those strings. In your case the value cat. However, an array is an object with reference comparison, not value comparison. So when comparing two arrays the reference will be compared. That is if you compare the same object to itself the result will be true. However, as is the case in your example, if you compare two different objects even with all the properties set to the same value, the result will be false.

let a = [1,2];
let b = 2;
let c = "string";
let d = [1,2];

a === a; //true reference comparison comparing an object to itself
b === 2; //true value comparison
c === "string"; //true again value comparison, even though it's two different objects
a === d; //false the values are the same but it's reference  comparison

Array.includes iterates through the array and makes a comparison between the argument and the individual elements using the above comparison types depending on the types.

It's also important to note that includes uses strict comparison. That is if a comparison with === results in true then so would includes. It's not enough that == would result in true. "2" == 2is an example of a comparison that returns true where ["2"].includes(2) returns false

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.