Sort one array the same way as another array JavaScript

后端 未结 4 1181
日久生厌
日久生厌 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:22

    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"]
    

提交回复
热议问题