Last Updated: February 25, 2016
·
262
· darhazer

Sort by keys in JS

To sort by keys, you first have to collect the keys in an array, then sort the array, and finally create a new object by copying the data from the original one in the order of the sorted array. Well, I provided a function that also may sort the keys not alphabetically, but in a user-specified order, similarly to MySQL's ORDER BY FIELD.

var sortByKeys: function(arr, fields) {
    var keys = [];
    for (var key in arr) {
      if (arr.hasOwnProperty(key)) {
        keys.push(key);
      }
    }

    if (typeof fields !== 'undefined') {
      keys.sort(function(a, b){
        return fields.indexOf(a) - fields.indexOf(b);
      });
    } else {
      keys.sort();
    }

    data = {};
    for (var i = 0, l = keys.length; i < l; i += 1) {
      var key = keys[i];
      data[key] = arr[key];
    }
    return data;
  }