Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda