Sort one array the same way as another array JavaScript

◇◆丶佛笑我妖孽 提交于 2020-06-08 07:40:45

问题


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?


回答1:


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
)



回答2:


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);



回答3:


I would recommend storing the entire thing in a Map. That way, you can independently sort the first array however you want and then use those values as keys to call respective value of second array.




回答4:


You can do this in a single line by associating your two arrays and then ordering the items:

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

const result = y.map((val, index)=>({x:x[index], y:val})).sort((a,b)=>a.y-b.y).map(v=>v.x)

// -> ["c", "e", "a", "f", "b", "d"]


来源:https://stackoverflow.com/questions/59601504/sort-one-array-the-same-way-as-another-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!