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

228
Visualizações
Find index of nested array

The code below should work but it doesn't. Does anyone know why?

const items = [
  ["bob", 5],
  ["jeff", 2],
  ["wal-E", 2],
  ["bob", 1],
  ["bob", 10]
];

items.indexOf(["bob", 5]);
//=> -1
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It does not because indexOf uses simple comparison when looking for a match and [] !== [] because arrays are compared by reference, not by their contents. Try typing [5]===[5] it will give you false.

So you will need to manually write comparison logic using findIndex.

let items = [
    ["bob", 5],
    ["jeff", 2],
    ["wal-E", 2],
    ["bob", 1],
    ["bob", 10]
];

console.log(items.findIndex(x => x[0] === "bob" && x[1] === 5))

about 4 years ago · Juan Pablo Isaza Relatório

0

Array#indexOf uses strict equality === for comparison. What you're wanting to do can only work if you hold a reference to the same array:

const x = [1, 2];

[[0, 1], [1, 2], [2, 3]].indexOf(x);
//=> -1

[[0, 1], x, [2, 3]].indexOf(x);
//=> 1

What you can do is use Array#findIndex and compare each element of each nested array with each element of x at the same index:

const indexOf = (xs, ys) => ys.findIndex(yy => {
  if (xs.length != yy.length) return false;
  return yy.reduce((b, y, i) => b && Object.is(y, xs[i]), true);
});

indexOf([], [[1],[],[2, 3]]);
//=> 1

indexOf([1, 2], [[1, 2, 3, 4], [1, 2, 3], [1, 2]]);
//=> 2

indexOf([1, 2], [[2, 3], [3, 4]]);
//=> -1

indexOf([9, 9, 9], [[9], [9, 9], [9, 9, 9]]);
//=> 2

indexOf([9, NaN, 9], [[9], [9, NaN, 9], [9, 9]]);
//=> 1
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