I have the associative array:
array["sub2"] = 1;
array["sub0"] = -1;
array["sub1"] = 0;
array["sub3"] = 1;
array["sub4"] = 0;
What is the most elegant way to sort (descending) by its values where the result would be an array with the respective indices in this order:
sub2, sub3, sub1, sub4, sub0?
There really isn't any such thing as an "associative array" in JavaScript. What you've got there is just a plain old object. They work kind-of like associative arrays, of course, and the keys are available but there's no semantics around the order of keys.
You could turn your object into an array of objects (key/value pairs) and sort that:
Then you'd call that with a comparator function.
Here is a variation of ben blank's answer, if you don't like tuples.
This saves you a few characters.
The best approach for the specific case here, in my opinion, is the one commonpike suggested. A little improvement I'd suggest that works in modern browsers is:
This could apply easily and work great in the specific case here so you can do:
Besides of this, I provide here a more "generic" function you can use to sort even in wider range of situations and that mixes the improvement I just suggested with the approaches of the answers by Ben Blank (sorting also string values) and PopeJohnPaulII (sorting by specific object field/property) and lets you decide if you want an ascendant or descendant order, here it is:
You can test the functionalities trying something like the following code:
As I already said, you can loop over sorted keys if you need doing stuffs
Last, but not least, some useful references to Object.keys and Array.sort
i use $.each of jquery but you can make it with a for loop, an improvement is this:
So now you can do