我有一個函式,它是一個按字母順序排序的字串,大寫字母在小寫字母之前。
group('aaAbbBCCcDdEE') //should return 'AaaBbbCCcDdEE'
function group(string){
return string.split("").sort(function(a, b) {
return a - b;
}) .join("");
}
- 對此進行排序的最佳方法是什么?
謝謝。
uj5u.com熱心網友回復:
添加檢查以查看您正在使用的內容。你真正關心的部分是是否a和b是相同的字符,如果其中一個是上層,一個是下層。
const result = 'aaAbbBCCcDdEE'.split('').sort((a, b) => {
// if they are the same, nothing to do
if (a === b) return 0;
// normalize the letters
const uA = a.toUpperCase();
const uB = b.toUpperCase();
// if they are the same letter when normalized, figure out what one is upper
if (uA === uB) return uA === a ? -1 : 1
// if not, just sort them by alphabet
return uA.localeCompare(uB);
}).join('');
console.log(result);
uj5u.com熱心網友回復:
我也有類似的想法。檢查字母是否相同但大小寫不同,使用按它們的 ASCII 值排序。
group('aaAbbBCCcDdEE') //should return 'AaaBbbCCcDdEE'
function group(string){
return string.split("").sort(function(a, b) {
return a !== b && a.toLowerCase() === b.toLowerCase() ? a.charCodeAt(0) - b.charCodeAt(0) : a - b;
}) .join("");
}
uj5u.com熱心網友回復:
謝謝 - 所有代碼都很好用 - 贊賞!
uj5u.com熱心網友回復:
您可以創建自定義排序方法,該方法適用于字符的 Ascii 值
一個 -> 97
A-> 65
因此,為了滿足您的需求,我們可以簡單地將小寫值代碼設定在兩個連續的大寫字母之間
即A -> 65, a -> 65.5, B-> 66, b-> 66.5 ...... Z-> 90, z-> 90.5
現在讓我們開始撰寫代碼
function getSortableCode(c)
{
const code = c.charCodeAt(0);
return code >= 97 ? code - 31.5 : code;
}
function doSort(str)
{
return str.split('').sort((a,b) => getSortableCode(a) - getSortableCode(b));
}
console.log('aaAbbBCCcDdEE after sorting becomes: ' doSort('aaAbbBCCcDdEE'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437120.html
標籤:javascript 排序
上一篇:R:將時間序列拆分為自定義季節
下一篇:awk日期變數
