开发者

Sorting Associative Array in Javascript

I am new to this board have been fishing for info here for a long time and this is my first time posting here. I am in sort of a jam right now I have an array in javascript that looks like this. Each ID is accociated with a persons name

        Array
         (
            [230] => Smith, Marc-Andre 
            [11369] => Smith, Wayne 
            [12561] => Smith, Diane 
            [12637] => Smirnova, Natalie
         )

Right now the array is sorted by the index which is the ID of the person. I am wondering if its possible to sort it alphabetically such that the array now looks like

          Array
          (
             [12637] => Smirnova, Natalia 
             [12561] => Smith, Diane 
             [230] => Smith, Marc-Andre 
             [11369] => Smith, Wayne       
          )

So far I tried using array.sort() it does sort alphabetically but the ID is lost it gives me

      Array
          (
             [0] => Smirnova, Natalia 
             [1] => Smith, Diane 
             [2] => Smith, Marc-Andre 
             [3] => Smith, Wayne       
 开发者_高级运维         )

This is my first time programming javascript so thanks for all the help in advance.


Store the entries as objects in an array, with ID and name properties. The JSON would look like:

[ {'id':230,'name':'Smith, Marc-Andre'}, {'id':11369,'name':'Smith, Wayne'}, {'id':12561,'name':'Smith, Diane'}, {'id':12637,'name':'Smirnova, Natalie'} ]

Then pass a function into Array.sort() to choose which property to sort on. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/sort


You can't use a simple array to do what you're asking for. An array is, by definition, a list of data that is ordered by the array indexes. You are asking for it to be ordered by something other than the array indexes. I think the simplest way to store it would end up like this:

   var myData = [
        [12637, "Smirnova, Natalia"], 
        [12561, "Smith, Diane"], 
        [230, "Smith, Marc-Andre"], 
        [11369, "Smith, Wayne"]
    ];

So, it would be an array of arrays, where each sub-array contains two items, the first is the id, the second is the name. This is a similar, but slightly different form what wmorrell proposed.

You can then sort the data by the last name by passing a custom comparision into the sort routine like this:

// custom sort (assumes all data is fully formed)
// sorts in ascending order by the 2nd item in each embedded array
    myData.sort(function(a,b) {
      if (a[1] < b[1]) return(-1);
      if (a[1] > b[1]) return(1);
      return(0); 
    });


You can do something like:

function arrayify(arg) {
    var ret = [];
    for (var i in arg) {
        if (!arg.hasOwnProperty(i) continue;
        ret.push({key: i, value: arg[i]});
    }
    return ret;
}

arr = arrayify(arr).sort(function(a, b) {
    return a.key.toString() - b.key.toString();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜