我想对地址数组进行排序。使用 .sort()
看起来很简单我的数组上的方法。
但是... 尝试在这里查看:https://jsfiddle.net/ytuzr918/
.sort()
方法按字母顺序完美排序(至少我认为是这样)。然而,我的地址有数字,数字后面甚至还有更多字母。
那么有没有一种方法可以“正确”地对数组进行排序,可能是通过对排序方法进行原型(prototype)设计?
最佳答案
您可以为 Array.prototype.sort()
提供比较函数。
改编 here 的答案:
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(addresses.sort(sortAlphanum));
关于javascript - Javascript 中的地址数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36860029/