我正在尝试使用JavaScript中的.sort()
方法对下面显示的数组进行排序。
var addresses = [
"5 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"51 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"53 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"55 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"57 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"7 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"9 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan"
];
但是,在调用.sort
方法之后,我将数组写入文档。该数组似乎不会更改为升序数字顺序。
谁能看到我出错的地方?
答案 0 :(得分:2)
您的数组包含字符串,因此它们将按字母顺序排序,而不是按数字顺序排序。您将要使用排序函数作为array.sort的参数并解析出门牌号。
答案 1 :(得分:1)
最后通过以下代码使用它:
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 || Infinity, $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]);
if(nn) return nn;
}
return ax.length - bx.length;
}
addresses = addresses.sort(naturalCompare);
答案 2 :(得分:1)
您可以使用此排序函数来比较字符串的第一个数字
var addresses = [
"5 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"51 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"53 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"55 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"57 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"7 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"9 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan"
];
addresses.sort(function(a, b){
return +a.split(" ")[0] - +b.split(" ")[0];
});
console.log(addresses);
答案 3 :(得分:0)
检查以下示例
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
答案 4 :(得分:0)
试试这个
var addresses = [
"5 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"51 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"53 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"55 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"57 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"7 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan",
"9 Glyn Eiddew, , , , Llanbradach, Caerphilly, Mid Glamorgan"
];
addresses.sort(function(a, b){
return a.split(' ')[0] - b.split(' ')[0]
})