2

I know I uploaded a similar question, but my intention is different here so this is not a duplicate question.

I want to sort an array based on another array of numbers. More specifically, if 1 is the nth element of the array of numbers, I want to rearrange the target array so that the nth element in the original array is the first element, and so on. For example;

    //Case 1
    const input = ["a", "b", "c", "d", "e"];
    const order = [2, 4, 5, 1, 3];

    intended_result: ["d", "a", "e", "b", "c"];

    //Case 2
    const input = ["a", "b", "c", "d", "e"];
    const order = [3, 1, 4, 5, 2];

    intended_result: ["b", "e", "a", "c", "d"];

What would be the Javascript code to do the above operation? Any suggestion?

Thanks a lot in advance!

Raghul SK
  • 1,256
  • 5
  • 22
  • 30
J.Ko
  • 6,561
  • 3
  • 12
  • 28
  • [Zip the arrays](https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) or [make an object from them](https://stackoverflow.com/questions/39127989/creating-a-javascript-object-from-two-arrays) then [use the result to sort by](https://stackoverflow.com/questions/39127989/creating-a-javascript-object-from-two-arrays). Easiest is probably make an object then `input.sort((a, b) => obj[a] - obj[b])` – VLAZ Jul 02 '20 at 07:23

2 Answers2

7

No need for sorting, you just need to apply the permutation that you have:

const result = [];
for (let i=0; i<order; i++)
  result[order[i]-1] = input[i];
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

This should be working:

const sorted = input.slice().sort((a, b) => {
    const indexA = input.indexOf(a);
    const indexB = input.indexOf(b);
    return order[indexA] - order[indexB];
});

We slice the input so it won't be mutated and change the index of values in the array.

Axnyff
  • 9,213
  • 4
  • 33
  • 37