簡體   English   中英

根據 JavaScript 中的另一個數組對數組進行排序

[英]Sorting an array according to another in JavaScript

我需要對一個數組進行排序,就像在這個例子中一樣。

Input : 

2 1 5 4 9 3 6 7 10 8

A B C D E F G H I J

Output : 

1 2 3 4 5 6 7 8 9 10 

B A F D C G H J E I 

這是 c++ 中的代碼,但我不知道 c++ 所以如果有人可以用 js 編寫它,我會非常感激/

您可以獲取數組的索引,按所需順序排序,map 將值及其索引排序。

 var order = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8], values = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], result = [...order.keys()].sort((a, b) => order[a] - order[b]).map(i => values[i]); console.log(...result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM