Home > Net >  JavaScript indexOf(), includes() not understandable behaviour
JavaScript indexOf(), includes() not understandable behaviour

Time:01-02

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...

CodePudding user response:

From the docs:

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

Here, you're trying to compare arrays which are not primitive values.

One way to compare arrays is to iterate and check every element, you can do this using Array#every if they have the same length.

Then, using Array#some, check if an array subArr is in mainArr.

const 
  mainArr = [ [1], [2] ],
  subArr = [1];
  
const isEqual = (arr1 = [], arr2 = []) => 
  arr1.length === arr2.length && arr1.every((e, i) => e === arr2[i]);
  
const result = mainArr.some(arr => isEqual(arr, subArr));

console.log(result);

CodePudding user response:

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

CodePudding user response:

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
         }
 
  • Related