我很難找到解決方案。
我有一個與此類似的陣列。
// Original array
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];
// The sorted array needs to be like this.
sorted_array = ["1", "1A", "01A", "2", "02B", "03B", "10"];
我曾嘗試撰寫這樣的自定義排序函式,但找不到解決方案。我很感激任何幫助。
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];
const sorted_array = orig_array.sort((a, b) => {
if (a - b) {
return a - b;
}
if (a.localeCompare(b) === -1) {
return a.length - b.length;
} else {
return 1;
}
});
console.log(sorted_array);
uj5u.com熱心網友回復:
您可以先應用parseInt到兩個字串以獲取第一個數字部分并減去它們。如果數字部分相等,則減去長度。
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];
console.log(orig_array.sort((a,b)=>parseInt(a)-parseInt(b)||a.length-b.length));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345966.html
標籤:javascript 算法 排序 自然排序
