Home > Back-end >  Reverse lookup array in javascript
Reverse lookup array in javascript

Time:11-04

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

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related