簡體   English   中英

根據數字數組對字符串數組進行排序

[英]Sort an array of strings based on an array of numbers


我正在嘗試執行以下操作:基於相等長度的數字數組對字符串數組進行排序。 例如:

A=[a,b,c,d,e]
B=[1,3,2,5,4]

A'=[a,c,b,e,d] //<=The desired outcome

基本上,我正在考慮基於將數組 B 排序為升序對數組 A 進行排序。 在這里,我正在考慮隱式值對,就像對象一樣。

我可以考慮創建一個對象,對其進行排序,然后將字符串數組分離出來,但這可能代碼太多,我想知道是否有更簡單的方法來實現這一點。
歡迎任何建議。 非常感謝!

你不需要在這里排序任何東西。
只需將數字用作“位置”,即可從中獲取結果中當前索引/位置的值。

 const input = ["a", "b", "c", "d", "e"]; const order = [1, 3, 2, 5, 4]; const result = order.map(position => input[position - 1]); console.log(result);

一點代碼高爾夫:

 const A=['a','b','c','d','e']; const B=[1,3,2,5,4]; // for this to work, we have to assume A and B have the same length // if you implement this into a function, do such a check yourself first const sorted = A.map((item, index, arr) => arr[B[index] - 1]); console.log(sorted);

只要 B 至少與 A 一樣長,並且 B 中填充了數字,這將起作用

您可以使用 for 循環並添加來自 A 的值,從 B 獲取索引。

 let A = ["a", "b", "c", "d", "e"]; let B = [1, 3, 2, 5, 4]; let C = []; for (let i = 0; i < A.length; i++) C[B[i] - 1] = A[i]; console.log(C);

如果您想要自定義訂單,那么您可以使用訂單創建一個對象:

 let a = ['a', 'b', 'c', 'd', 'e']; let b = [1, 3, 2, 5, 4]; let order = {a: 1, b: 3, c:2, d: 5, e:4}; const result = a.sort((a, b) => order[a] - order[b]); console.log(result);

暫無
暫無

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

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