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