簡體   English   中英

如何按字典順序對字符串數組進行排序 JavaScript

[英]How to sort lexicographically array of strings JavaScript

如何對例如 [aa bb cc dd ee] 的字典數組進行排序,其中您取第一個字典序最小的名稱並將其附加到字典序最大的名稱,然后取第二個字典序最小的名稱並將其附加到第二個字典序最大的名稱。 如果你有像這里 cc 這樣的奇數個元素,我想輸出應該是 eeaaccddbb 作為一個完整的字符串。 我在 Mozilla 開發人員工具中找不到用於按字典順序排列的數組的功能。 如果它們是數組的偶數個元素,則僅返回相應的串聯。

這里有個好東西:p

 function weirdSortConcat(arr) { // sort lexicaly by default // to be exact sort by char code so digits(0-9) are before maj(AZ) which are before min(az) arr.sort() let output = "" // for half of the array for (let i = 0; i < Math.floor(arr.length / 2); i++) { // take starting at the end then starting by the start output += arr[arr.length - i - 1] + arr[i] } // if length is odd add last element to output if (arr.length % 2 === 1) { output += arr[Math.floor(arr.length / 2)] } return output } console.log(weirdSortConcat(["aa", "bb", "cc"])) console.log(weirdSortConcat(["aa", "cc", "bb"])) console.log(weirdSortConcat(["aa", "bb", "cc", "dd"]))

暫無
暫無

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

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