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

76
Vistas
Reverse lookup array in javascript

how do you create a reverse lookup array in an efficient way?

e.g. [5, 3, 1, 4, 2] => [3, 5, 2, 4, 1]

Obviously a simple way is:

const input = [5, 3, 1, 4, 2];
const output = [];
for (i = 0; i < input.length; i++) {
    output[input[i] - 1] = i + 1;
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your method is O(n): I don't think that can be beaten

You do have to go across every element in the input (to read it) and every element of the output (to write it): there is no getting out of that!

My only suggestion to slightly speed it up is to pre-size the output array.

const input = [5, 3, 1, 4, 2];
const output = new Array(input.length);
input.forEach(
  (value, i) => output[value - 1] = i + 1
)

console.log(output)

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