Som*_*der 6 javascript arrays sorting
我有 2 个数组:
[2, 4, -2, 4, 1, 3]
["a", "b", "c", "d", "e", "f"]
Run Code Online (Sandbox Code Playgroud)
我希望它们按数值数组排序:
// 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
Run Code Online (Sandbox Code Playgroud)
虽然如果 "b" 或 "d" 先出现实际上并不重要(在这个例子中它们都有 4 个)
我在网上发现了很多关于这个的问题,但没有一个对我有用,谁能帮我解决这个问题?
keys您可以根据第一个数组的值对它们进行排序。这将返回一个数组,其中数组的索引根据numbers数组的值排序。然后用于map根据索引获取排序后的值
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
)Run Code Online (Sandbox Code Playgroud)