Search code examples
javascriptarrayssorting

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.


Solution

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