Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over a Javascript associative array in sorted order

Tags:

javascript

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).

like image 277
mike Avatar asked May 20 '09 23:05

mike


2 Answers

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)

like image 133
molnarg Avatar answered Sep 17 '22 22:09

molnarg


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"; 
like image 32
Matthew Avatar answered Sep 19 '22 22:09

Matthew