Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda