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

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

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 Denunciar

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