0

I can't find explanation to the following. Why is this happening?

let mainArr = [ [1], [2] ]
let subArr = [1]
let result = mainArr.includes(subArr)     *//output: false*

also

let mainArr = [ [1], [2] ]
let subArr = [1]
let result = mainArr.indexOf(subArr)     *//output: -1*

This is my original code:

let mainArr =  [ [ 'apple', 1 ], [ 'bat', 2 ], [ 'cookie', 2 ] ] 
let subArr = [ [ 'apple', 1 ] ]     *//with let subArr = [ 'apple', 1 ] will be also -1*
let result = mainArr.indexOf(subArr)     *//output: -1*

I don't get it...

  • Probably a duplicate but.. arrays are reference types and they are compared over references so: `[] === []` is always false. – Eldar Jan 01 '22 at 21:01

2 Answers2

0

The array [1] which is the first element of the mainArr variable and the other array [1], which is the value of the subArr variable are not the same array. They are two different arrays, both having 1 as the only element. That's why you get false when you call includes and you get -1 when you call indexOf. If you want it to be the same array, you can do the following:

let subArr = [1]; // create the [1] array and store a reference to it inside the subArr variable
let mainArr = [subArr, [2]]; // assign the subArr variable as the first element of the mainArr array
let result = mainArr.includes(subArr); // result is true
0

Arrays are considered Objects in javascript. Only primitive types, like strings and integers, can be compared by their value in javascript. Unfortunately Objects are compared by their reference (aka the place they are stored in memory). -- Every time an object is created, it is given a reference to a space where it is stored in memory -- So, even though an object may look identical, its reference is not.

To compare both you would have to traverse one array and compare each value to the corresponding index of the second array. Something like:


      for (let i = 0; i < mainArr.length; i++){
         if (mainArr[i] !== subArr[i]){
            //not the same
         } else {
            continue
         }
 
knicholas
  • 520
  • 4
  • 10