[英]In javascript sorting strings with numbers and special characters
我正在嘗試使用數字和特殊字符組合對字符串進行排序。
但它給出了錯誤的命令。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function MySort(alphabet)
{
return function(a, b) {
var index_a = alphabet.indexOf(a[0]),
index_b = alphabet.indexOf(b[0]);
if (index_a === index_b) {
// same first character, sort regular
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
return index_a - index_b;
}
}
}
function myFunction() {
var items = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"
],
sorter = MySort('*!@_.()#^&%-=+01234567989abcdefghijklmnopqrstuvwxyz');
console.log(items.sort(sorter));
}
</script>
</body>
</html>
它給出了以下回應。 [“AB_UI01”、“AB_UI010”、“AB_UI011”、“AB_UI012”、“AB_UI013”、“AB_UI014”、“AB_UI015”、“AB_UI016”、“AB_UI017”、“AB_UI018”、“AB_UI010” AB_UI020”、“AB_UI03”、“AB_UI04”、“AB_UI05”、“AB_UI06”、“AB_UI07”、“AB_UI08”、“AB_UI09”]
未排序數組:["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012" ","AB_UI06","AB_UI016","AB_UI017","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"]
預期輸出:[“AB_UI01”、“AB_UI02”、“AB_UI03”、“AB_UI04”、“AB_UI05”、“AB_UI06”、“AB_UI07”、“AB_UI08”、“AB_UI09”、“AB_UI010”、“AB_UI01012AB” ", "AB_UI013", "AB_UI014", "AB_UI015", "AB_UI016", "AB_UI17", "AB_UI018", "AB_UI019", "AB_UI020"]
感謝您的建議。
如果您喜歡按組排序,例如字母和/或數字,您可以使用String#localeCompare
選項進行排序。
var array = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"]; console.log(array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })));
.as-console-wrapper { max-height: 100% !important; top: 0; }
鑒於您的單詞(例如AB_UI08
)似乎類似於{letters}{digits}
,其中letters
不是digits
和[0-9]+
形式的digits
。
即: letters==AB_UI
和d==08
。
假設您想先按字母排序,然后按數字排序。
您可以將您的單詞映射到字母和數字,然后為了比較兩個單詞,如果它們的字母部分相等,則比較它們的數量。
function toObj(w) { const letters = w.match(/^[^\\d]+/)[0] return { w, letters, d: parseInt(w.replace(letters,'')) } } const items = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"] const sorted = items.map(toObj).sort((a,b) => { const res = a.letters.localeCompare(b.letters) return res !== 0 ? res : ad - bd }).map(x => xw) console.log('sorted', sorted)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.