按对象属性排序javascript数组

时间:2014-08-20 04:18:50

标签: javascript sorting

我想通过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 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题。

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;
})