Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!