0

Possible Duplicate:
Sort JavaScript object by key

{
    "0": 3900,
    "1": 42,
    "10": 135,
    "2": 5,
    "3": 20,
    "4": 33,
    "5": 24,
    "6": 35,
    "7": 56,
    "8": 60,
    "9": 147
}

How to sort javascript keys based on the key integer Type. for the above given input the final output should be in format of

{
0: 39,
1: 42,  
2: 5,
3: 20,
4: 33,
5: 24,
6: 35,
7: 56,
8: 60,
9: 147,
10: 135,
}
Community
  • 1
  • 1
Ugesh Gali
  • 2,042
  • 4
  • 20
  • 24

1 Answers1

1

That's an JavaScript Object. They can't be sorted.

For example, no matter what order you place your elements in, in the code, Google Chrome will automatically sort them when you log the object.

var obj = {
    "0": 3900,
    "1": 42,
    "10": 135,  // See? not sorted.
    "2": 5,
    "3": 20,
    "4": 33,
    "5": 24,
    "6": 35,
    "7": 56,
    "8": 60,
    "9": 147
}
for(key in obj){
    console.log(key, obj[key]);
}

Output:

0 3900
1 42
2 5
3 20
4 33
5 24
6 35
7 56
8 60
9 147
10 135  // Suddenly, without our intervention, the object got sorted by the browser.

So, what I am trying to say is: It's browser-dependent. You can't sort objects. It depends on the browser implementation how the object will be iterated over.

Now, in this specific case, I think it's a better idea to just use an array, since the keys are sequential numbers, any way:

var arr = [3900, 42, 5, 20, 33, 24, 35, 56, 60, 147, 135];

You can access this the same way as you would access your object (arr[5] == 24), and as an added bonus, it has a .length!

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Need to support not only in chrome but also IE and FF – Ugesh Gali Jan 08 '13 at 09:04
  • 2
    @ugesh.gali You're missing the point here: the example demonstrates that you can't rely on an object being sorted, because it is by specification always unsorted. You simply **can't** sort an object; you need to use an intermediary array or sort the object on the fly when you need the sorted data. – JJJ Jan 08 '13 at 09:09
  • @ugesh.gali: Edited my answer to clarify. – Cerbrus Jan 08 '13 at 09:10