Sort one array the same way as another array JavaScript

后端 未结 4 1073
日久生厌
日久生厌 2021-01-12 16:42

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:

<
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 17:45

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

提交回复
热议问题