0

I need to sort one array same as other array like in this example.

Input : 

2 1 5 4 9 3 6 7 10 8

A B C D E F G H I J

Output : 

1 2 3 4 5 6 7 8 9 10 

B A F D C G H J E I 

Here is code in c++ but I don't know c++ so if someone can write it in js I would be very greatful https://www.geeksforgeeks.org/sorting-array-according-another-array-using-pair-stl/

0

1 Answer 1

1

You could take the indices of an array, sort by the wanted order and map the values with their index.

var order = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8],
    values = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
    result = [...order.keys()]
        .sort((a, b) => order[a] - order[b])
        .map(i => values[i]);

console.log(...result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.