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

207
Vistas
Finding the index of an array in an array using higher order functions?

I can find whether an array exists in another array:

const arr1 = [[1,2,3],[2,2,2],[3,2,1]];

const match = [2,2,2];

// Does match exist
const exists = arr1.some(item => {
  return item.every((num, index) => {
    return match[index] === num;
  });
});

And I can find the index of that array:

let index;
// Index of match
for(let x = 0; x < arr1.length; x++) {
  let result;
  for(let y = 0; y < arr1[x].length; y++) {
    if(arr1[x][y] === match[y]) { 
      result = true; 
    } else { 
      result = false; 
      break; 
    }
  }
  
  if(result === true) { 
    index = x; 
    break;
  }
}

But is it possible to find the index using JS' higher order functions? I couldn't see a similar question/answer, and it's just a bit cleaner syntax wise

Thanks

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could take Array#findIndex.

const
    array = [[1, 2, 3], [2, 2, 2], [3, 2, 1]],
    match = [2, 2, 2],
    index = array.findIndex(inner => inner.every((v, i) => match[i] === v));

console.log(index);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another approach transform the inner-arrays of array into strings like ['1,2,3', '2,2,2', '3,2,1'] and also transform the matching array into string 2,2,2. then use built-in function indexOf to search of that index in array.

const arr1 = [[1,2,3],[2,2,2],[3,2,1]];
const match = [2,2,2];

const arr1Str = arr1.map(innerArr=>innerArr.toString());
const index = arr1Str.indexOf(match.toString())
console.log(index);

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