自然數組元素排序:帶有數字的字符串
自然數組元素排序:帶有數字的字符串
本文深入研究了對包含在a 中組合字符串和數字的元素的陣列進行排序的任務自然順序,排序過程中應考慮字串內的數字序列。
The問題
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]考慮這樣的陣列:
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]考慮這樣的陣列:
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob said hello"]
如果我們嘗試使用傳統的排序函數對此數組進行排序,我們可能會得到不正確的順序:["IL0 Foo", "IL10 Baz", "IL3 Bob said hello", "PI0 Bar"]["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]
解決方案:自然排序
要實現自然排序,我們可以利用以下方法JavaScript函數:
function naturalCompare(a, b) { var ax = [], bx = []; a.replace(/(\d )|(\D )/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) }); b.replace(/(\d )|(\D )/g, function(_, $1, $2) { bx.push([$1 || 無窮大, $2 || ""]) }); while(ax.length && bx.length) { var an = ax.shift(); var bn = bx.shift(); var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]); 如果(nn)返回nn; } 返回 ax.length - bx.length; }此函數將輸入字串標記為數字和非數字值的陣列。然後,它按字典順序比較數組,同時考慮整數值和字串非數字值。["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]
範例
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]將此函數應用於給定數組結果是所需的自然排序順序:
test = [
“img12.png”,
“img10.png”,
“img2.png”,
“img1.png”,
“img101.png”,
“img101a.png”,
"abc10.jpg",
“abc10”,
"abc2.jpg",
"20.jpg",
“20”,
“abc”,
“abc2”,
””
];
測試.排序(自然比較)
document.write("
" JSON.stringify(test,0,3));這會產生以下排序數組:[ "", “abc”, “abc2”, “abc10”, "abc10.jpg", “20”, "20.jpg", “img1.png”, “img2.png”, “img10.png”, “img12.png”, “img101.png”, “img101a.png” ]
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3