[英]sort javascript array by object attribute
我想按lastName屬性對數組進行排序。 數組保持完全相同。 這是代碼:
console.log(clientListArray);
//sort clientList by last name
var sortedtClientListArray = clientListArray.sort(function(obj1, obj2) {
console.log(obj1.lastName);
return obj1.lastName - obj2.lastName;
})
console.log(sortedtClientListArray);
我的數組的console.log保持不變(分為第4個元素(索引3)):
0: ct.extend.init
1: ct.extend.init
2: ct.extend.init
3: ct.extend.init
_events: Object
dwelling: "RH07"
firstName: "Alan"
lastName: "Mosby"
letter: "M"
nhi: ""
oid: "2143.10"
parent: function (){return i}
uid: "79fbbf40-5545-4cdc-bc2b-088bf56affc6"
__proto__: r
4: ct.extend.init
5: ct.extend.init
6: ct.extend.init
7: ct.extend.init
length: 8
__proto__: Array[0]
為什么數組中對象的順序沒有變化?
它里面的完整方法是:
function onClientClick(e) {
console.log(e.dataItem);
var clientList = e.sender.dataSource._data;
console.log(clientList);
var clientListArray = [];
for(i=0; i < clientList.length; i++){
clientListArray.push(clientList[i]);
}
console.log(clientListArray);
//sort clientList by last name
var sortedtClientListArray = clientListArray.sort(function(obj1, obj2) {
console.log(obj1.lastName);
return obj1.lastName - obj2.lastName;
})
console.log(sortedtClientListArray);
for(i=0; i < clientList.length; i++){
var clientID = clientList[i].oid;
if(clientID == e.dataItem.oid) {
theClient = new Client(clientList[i]);
console.log(i);
console.log(theClient.name);
navigateToSingleClient(true, clientList[i], true, clientList, i);
}
}
}
您的代碼中有兩個問題。
1) "OneString"-"SecondString"
將返回NaN
。 因此,在這種情況下,ca可以將其退回。
2) Array.sort
對給定的數組進行排序。 它返回排序后的數組。
這樣說
clientListArray.sort(function(a, b){
if(a.lastName < b.lastName) return -1;
if(a.lastName > b.lastName) return 1;
return 0;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.