I need to sort associative array by JS for one of my projects. I found this function, that works great in firefox, but unfortunately it doesnt work in IE8, OPERA, CHROME... Cant find the way to make it work in other browsers, or find another function that would fit the purpose. I really appreciate any help.

3 Answers
3

This is impossible. An Object in JavaScript (which is what you're using as your "associative array") is specified as having no defined order when iterating over its properties using a for...in loop. You may be able to observe some common ground between some browsers' behaviour, but it's not universal.

I recently ran into this problem and found this question. I was disappointed to find that there was no pre-defined way to sort an associative array, but it made sense and pointed me in the right direction. I didn't fully realize that in JS associative arrays are really objects and are only arrays in name. I had an associative array that contained more associative arrays, ex:

The following function will sort the above parent array based upon it's keys. For this to work as written, the parent array needs keys that match a value in the associated array. For instance, parent['unique string'] will need to have some key value that holds a value of 'unique string'. In my case, this is the name key; however, you can choose any key you like.

I know, it's meant to show the structure, not how you would actually define the array.
–
David MyersNov 21 '12 at 4:41

Which means that it doesn't show the structure. The pseudocode is ambiguous. It could either mean { key : [], key : [] } or it could mean [ {key:[]}, {key:[]} ]. From your code it looks like it means the latter. So you should have written it as such.
–
slebetmanNov 21 '12 at 5:39

As far as the array is concerned, it's a parent associative array which contains child associative arrays. Also, as far as [] vs {}, you realize that associative arrays in JS are really just objects and are accessed the same way so that's a moot point. And in reference to your question, it's the former, not the latter. Also, I've edited my answer to no longer use pseudocode and to be more clear.
–
David MyersNov 21 '12 at 16:36