Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this associative array :

Arr =  {
     "ID1":{"Attr1":"b","Attr2":"5"},
     "ID2":{"Attr1":"d","Attr2":"2"},
     "ID3":{"Attr1":"h","Attr2":"8"}
     }

and I want to sort it with the attribute 2 by numbers and not the ID in descending Order to obtain this result :

Arr =  { 
     "ID3":{"Attr1":"h","Attr2":"8"}
     "ID1":{"Attr1":"b","Attr2":"5"},
     "ID2":{"Attr1":"d","Attr2":"2"},
     }

If this possible ?

Thank you.

share|improve this question

closed as not a real question by Dagg Nabbit, Vega, jusio, 0x499602D2, Edwin Dalorzo Dec 7 '12 at 2:08

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

2 Answers

up vote 3 down vote accepted
Object.keys( Arr ).sort(function( a, b ) {
    return +Arr[ b ].Attr2 - +Arr[ a ].Attr2;
}).forEach(function( key ) { 
    console.log( key );
});

By invoking Object.keys and Array.prototype.sort, you can at least sort the keys of any object. With that, you can access those key / value pairs in order.

The output of the above snippet is

ID3
ID1
ID2
share|improve this answer
I think you meant return Arr[a].Attr2 - Arr[b].Attr2 – troelskn Dec 6 '12 at 21:15
actually it is Arr[b].Attr2 - Arr[a].Attr2 – jAndy Dec 6 '12 at 21:21
1  
My output is the same: ID1, ID2, ID3 nothing is changed. – Slim Mils Dec 6 '12 at 21:32
1  
$.each(Arr, function(ID) {alert(ID);}); => ID1, ID2, ID3 – Slim Mils Dec 6 '12 at 22:09
1  
Have you tested your code ? – Slim Mils Dec 6 '12 at 22:25
show 3 more comments

Javasript does not have associative arrays - it's an object. And in Javascript, the order of an objects properties aren't guaranteed. So before you can begin to sort anything, you will first need to convert your data into an array.

From there, it's just a matter of calling sort on the array.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.