Sort JavaScript Object by Key or Value

This is a quick tip for sorted access to JavaScript object by key or value.

Sorted Access Using Object Keys

Let’s say you have an object like this.

var obj = {
   mobile  : 'Firefox OS',
   desktop : 'Ubuntu',
   tablet  : 'Android'
};

Now you need to iterate over object properties in this order.

//sorted access using key
obj['desktop']
obj['mobile']
obj['tablet']

Here’s the functional way of doing it.

If you are new to functional programming, you can check my post on Functional Programming Using JavaScript.

Object.keys(obj)
      .sort()
      .forEach(function (k) {
         console.log(obj[k]);
      });

keys() return an array containing all the own property names of passed object. Then those keys are sorted using sort() method and those sorted keys are then iterated using forEach(). Finally the value of current key “k” is printed on console in the function passed to forEach().

Sorted Access Using Object Values

Let’s say you want to iterate over the same obj using values like this.

//sorted access using values
obj['tablet']  //Android
obj['mobile']  //Firefox OS
obj['desktop'] //Ubuntu
var keys = [];
 
Object.keys(obj)
      .map(function (k) { return [k, obj[k]]; })
      .sort(function (a, b) {
         if (a[1] < b[1]) return -1;
         if (a[1] > b[1]) return 1;
         return 0;
      })
      .forEach(function (d) {
         keys.push(d[0]);
         console.log(d[1]);
      });
 
//now keys array contain keys of obj in sorted order of values
console.log(keys);

First own property names are extracted using keys() method. Then map() method is used to transform each key-value pair into an array [key, value]. After transforming each key-value into an array, map() in the end returns two-dimensional array in which outer array contain all those smaller [key, value] arrays.

[
   ['mobile', 'Firefox OS'],
   ['desktop', 'Ubuntu'],
   ['tablet', 'Android']
]

Then this two dimensional array is sorted using sort() method. As you know now that each item in above array is itself an array so the anonymous function passed to sort() method actually sorts using index 1 (a[1], b[1]) because this is where the value is stored for each object property.

The final forEach() is used to add sorted property names in keys array and optional logging of value is done using console.log.


comments powered by Disqus