如何按字典顺序对字符串数组进行排序 JavaScript
How to sort lexicographically array of strings JavaScript
如何按字典顺序对数组进行排序[aa bb cc dd ee] 你取第一个字典序最小的名字并将它附加到字典序最大的名字,然后取第二个字典序最小的名字并将它附加到第二个字典序最大的名字。如果你有奇数个元素,比如这里的 cc,我猜输出应该是 eeaaccddbb 作为一个完整的字符串。我在 Mozilla Developer 工具中找不到用于字典顺序排列的函数。而如果它们是偶数个数组的元素,则只需将 return 对应的串联即可。
这里有一些好东西:p
function weirdSortConcat(arr) {
// sort lexicaly by default
// to be exact sort by char code so digits(0-9) are before maj(A-Z) which are before min(a-z)
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"]))
如何按字典顺序对数组进行排序[aa bb cc dd ee] 你取第一个字典序最小的名字并将它附加到字典序最大的名字,然后取第二个字典序最小的名字并将它附加到第二个字典序最大的名字。如果你有奇数个元素,比如这里的 cc,我猜输出应该是 eeaaccddbb 作为一个完整的字符串。我在 Mozilla Developer 工具中找不到用于字典顺序排列的函数。而如果它们是偶数个数组的元素,则只需将 return 对应的串联即可。
这里有一些好东西:p
function weirdSortConcat(arr) {
// sort lexicaly by default
// to be exact sort by char code so digits(0-9) are before maj(A-Z) which are before min(a-z)
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"]))