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

237
Visualizações
JavaScript - find index of array inside another array

I am trying to find the index of an array inside another array in Javascript, as below:

const piece = [5, 10];
const array = [[5, 10], [5, 11]];

//Using indexOf
console.log(array.indexOf(piece));

//Using findIndex
console.log(array.findIndex(function(element) {
  return element == piece;
  }));

I'm expecting these to return a 0 as that is the index where my "piece" is inside the larger array, but both methods return -1

Any ideas why this is happening? And if there is a different way for me to do this?

Thanks.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

To compare the actual values you can use the JSON.stringify() method:

piece = [5, 10];
array = [[5, 10], [5, 11]];

//Using findIndex
console.log(array.findIndex(function(element) {
    return JSON.stringify(element) == JSON.stringify(piece);
    }));

about 4 years ago · Juan Pablo Isaza Relatório

0

You are comparing objects (arrays) that were created each on their own, so they are not the same objects. If you want, you can compare each of the integers inside the arrays, and when also the array lengths match, you can conclude they are the "same":

piece = [5, 10];
array = [[5, 10], [5, 11]];

//Using findIndex
console.log(array.findIndex(function(element) {
  return element.length === array.length 
      && element.every((val, i) => val == piece[i]);
}));

about 4 years ago · Juan Pablo Isaza Relatório

0

Arrays in JavaScript are not compared by value, but by reference. So if you have arrays a and b like this:

const a = [1, 2];
const b = [1, 2];

When you compare them using ==, or === then their references are compared, not values. So this console.log(a == b), or console.log(a === b) will print false.

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