Let's say I have a Javascript associative array (a.k.a. hash, a.k.a. dictionary):
var a = new Array(); a['b'] = 1; a['z'] = 1; a['a'] = 1;
How can I iterate over the keys in sorted order? If it helps simplify things, I don't even need the values (they're all just the number 1).
You can use the Object.keys built-in method:
var sorted_keys = Object.keys(a).sort()
(Note: this does not work in very old browsers not supporting EcmaScript5, notably IE6, 7 and 8. For detailed up-to-date statistics, see this table)
You cannot iterate over them directly, but you can find all the keys and then just sort them.
var a = new Array(); a['b'] = 1; a['z'] = 1; a['a'] = 1; function keys(obj) { var keys = []; for(var key in obj) { if(obj.hasOwnProperty(key)) { keys.push(key); } } return keys; } keys(a).sort(); // ["a", "b", "z"]
However there is no need to make the variable 'a' an array. You are really just using it as an object and should create it like this:
var a = {}; a["key"] = "value";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With