简体   繁体   中英

How to sort lexicographically array of strings JavaScript

How to sort lexicographically array of eg [aa bb cc dd ee] where the you take the first lexicographically smallest name and append it to the lexicographically largest name, Then take the second lexicographically smallest name and append it to the second lexicographically largest name. And if you have odd number of elements like here cc the output i guess should be eeaaccddbb as a whole string. There is no function i found in Mozilla Developer tools for lexicographically array. And if they are even number of elements of array just to return the corresponding concatenations.

Here's something good :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"]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM