Reputation: 83
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.
Upvotes: 0
Views: 1549
Reputation: 208475
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;
});
Upvotes: 0
Reputation: 12196
Simple solution will be:
a.sort(function(x, y) {
return x.name - y.name;
})
Upvotes: 1
Reputation: 977
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.
Upvotes: 0