Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort one array the same way as another array JavaScript

I have 2 arrays:

[2, 4, -2, 4, 1, 3]
["a", "b", "c", "d", "e", "f"]

and I want them to be sorted by the numerical array:

// output
[-2, 1, 2, 3, 4, 4] // <-sorted by numerical order
["c", "e", "a", "f", "b", "d"] // sorted exactly the same order as the first array

while its actually not important if "b" or "d" comes first (they both have 4 in this example)

I found many questions about this online but none of them worked for me can anyone help me with that?

like image 445
SomeCoder Avatar asked Jan 05 '20 15:01

SomeCoder


1 Answers

You could sort the keys of the first array based on their value. This will return an array with indices of the array sorted based on the value of numbers array. Then use map to get the sorted values based on the indices

const numbers = [2, 4, -2, 4, 1, 3],
      alphabets = ["a", "b", "c", "d", "e", "f"]

const keys = Array.from(numbers.keys()).sort((a, b) => numbers[a] - numbers[b])

const sortedNumbers = keys.map(i => numbers[i]),
      sortedAlphabets = keys.map(i => alphabets[i])

console.log(
  sortedNumbers,
  sortedAlphabets
)
like image 138
adiga Avatar answered Oct 15 '22 16:10

adiga