0

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.

6
  • You mean: "Here's my array, but I really want an object"? And objects have no order...
    – elclanrs
    Commented Jan 16, 2014 at 20:01
  • 2
    That isn't an array, it is an object. JavaScript arrays have strictly numeric keys, but objects use the [] syntax to access properties when they are dynamically determined. Otherwise they would be dot properties. (technically you declared it as an array, but then added additional object properties to it) Commented Jan 16, 2014 at 20:01
  • And, object properties in JavaScript are inherently not ordered. Commented Jan 16, 2014 at 20:01
  • stackoverflow.com/questions/21027971/…
    – Dalorzo
    Commented Jan 16, 2014 at 20:02
  • 2
    Use a collection: [{name:'pml',val:44},{name:'pco',val:56},...]
    – elclanrs
    Commented Jan 16, 2014 at 20:03

3 Answers 3

1

Simple solution will be:

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

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

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.

1
  • Think you can just do return a.name > b.name.
    – elclanrs
    Commented Jan 16, 2014 at 20:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.