Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
JavaScript indexOf(), includes() not understandable behaviour

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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
about 4 years ago · Juan Pablo Isaza Report

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
         }
 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!