有時需要在前端進行排序時,可透過String.localeCompare()來進行比對。
var v1 = "abc";
var v2 = "def";
console.log(v1.localeCompare(v2));// -1
console.log(v2.localeCompare(v1));// 1
console.log(v1.localeCompare(v1));// 0
所以當有一個Object的Array需要進行排序時,可寫成如下
var objectAry = [
{userName:'John Doe',age:20}
,{userName:'Peter Hancock',age:42}
,{userName:'May J.',age:16}
];
{userName:'John Doe',age:20}
,{userName:'Peter Hancock',age:42}
,{userName:'May J.',age:16}
];
var compareAttr = 'userName';
objectAry.sort(function (o1,o2) {
return o1[compareAttr].localeCompare(o2[compareAttr]);
}).forEach(function(row,index){
console.log("row:" + index, row);
});
objectAry.sort(function (o1,o2) {
return o1[compareAttr].localeCompare(o2[compareAttr]);
}).forEach(function(row,index){
console.log("row:" + index, row);
});
row:0 Object {userName: "John Doe", age: 20}
row:1 Object {userName: "May J.", age: 16}
row:2 Object {userName: "Peter Hancock", age: 42}
由於localeCompare只有String才有,所以若直接用Number的資料以localeCompare的方式排序會出現錯誤。
compareAttr = 'age';
objectAry.sort(function (o1,o2) {
return o1[compareAttr].localeCompare(o2[compareAttr]);
}).forEach(function(row,index){
console.log("row:" + index, row);
});
objectAry.sort(function (o1,o2) {
return o1[compareAttr].localeCompare(o2[compareAttr]);
}).forEach(function(row,index){
console.log("row:" + index, row);
});
Uncaught TypeError: o1[compareAttr].localeCompare is not a function
所以可透過prototype的方式將Number資料型態增加localeCompare的function來處理。
Number.prototype.localeCompare = function (compare) {
if (isNaN(compare)) {//用於資料為String and Number混合比對的時候
return (this + "").localeCompare(compare);
} else if (this > compare) {
return 1;
} else if (this < compare) {
return -1;
} else {
return 0;
}
};
if (isNaN(compare)) {//用於資料為String and Number混合比對的時候
return (this + "").localeCompare(compare);
} else if (this > compare) {
return 1;
} else if (this < compare) {
return -1;
} else {
return 0;
}
};
再次執行
compareAttr = 'age';
objectAry.sort(function (o1,o2) {
return o1[compareAttr].localeCompare(o2[compareAttr]);
}).forEach(function(row,index){
console.log("row:" + index, row);
});
objectAry.sort(function (o1,o2) {
return o1[compareAttr].localeCompare(o2[compareAttr]);
}).forEach(function(row,index){
console.log("row:" + index, row);
});
row:0 Object {userName: "May J.", age: 16}
row:1 Object {userName: "John Doe", age: 20}
row:2 Object {userName: "Peter Hancock", age: 42}