I have two arrays:
arr1 = [4,2,3,5,1]
arr2 = ['a','b','c','d','e']
And if I apply an sorting algorithm to arr1, (e.g. by smaller number) it should update the indexes in the same way on arr2 (if arr1’s 4, before in index 0 gets moved to index 3, arr2’s value in index 0 gets moved to index 3).
ex.
arr1 = [1,2,3,4,5]
arr2 = ['e','b','c','a','d']
I’ve tried working with the JS sort function to no avail. Because the numbers in the arrays may be duplicates, indexOf()
doesn’t work. I don’t feel I need to implement my own sorting algorithm because I really feel like an elegant way is possible here.
2
Answers
Using an extra array should work for you something like this:
You can achieve this by combining Array 1 and Array 2 to one single array and then sorting the combined array by the values of array one.
Refer the code below :