简体   繁体   中英

Sort javascript array with non-numeric keys

Here is my array :

var a = [];
a["P.M.L."] = 44;
a["P.CO."] = 56;
a["M.É.D."] = 10;

Now i am trying to sort the array so it looks like :

["M.É.D." : 10, "P.M.L." : 44, "P.CO." : 56]

I have tried many solutions and none of them have been successfull. I was wondering if one of you had any idea how to sort the array.

Simple solution will be:

a.sort(function(x, y) { 
    return x.name - y.name;
})

Taken straight from the MDN website :

a.sort(function (a, b) {
    if (a.name > b.name)
      return 1;
    if (a.name < b.name)
      return -1;
    // a must be equal to b
    return 0;
});

But this really isn't an array, so you'll have to restructure that into one.

As mentioned in comments, your issue here is not just the sorting but also how your data structure is set up. I think what you will actually want here is an array of objects, that looks something like this:

var a = [{name: "P.M.L", val: 44},
         {name: "P.CO.", val: 56},
         {name: "M.É.D.", val: 10}];

With this new way of organizing your data, you can sort a by the val property with the following code:

a.sort(function(x, y) {
    return x.val - y.val;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM