Sort one array the same way as another array JavaScript
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
)
A standard method is to take the indices of the key array for sorting and sort the indices as pattern for all other arrays by taking the index and the value from the key array.
At the end map the sorted arrays.
var array1 = [2, 4, -2, 4, 1, 3],
array2 = ["a", "b", "c", "d", "e", "f"],
indices = [...array1.keys()].sort((a, b) => array1[a] - array1[b]);
[array1, array2] = [array1, array2].map(a => indices.map(i => a[i]));
console.log(...array1);
console.log(...array2);