In my last project at work, I had to work with fairly large data structures in Javascript. More than once I needed to sort data stored in Javascript objects. Javascript objects are by definition unsorted, so naturally there is no built-in way of doing this. All browsers, however, keep objects in the order that properties were added, so I decided to write a comprehensive sorting function.
This function will sort a Javascript object by key, value or predicate function, by transforming it to a temporary array and using the built-in Array.sort() on that. Here it is in all its glory:
sortObj = function(obj, type, caseSensitive) {
var temp_array = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (!caseSensitive) {
key = (key['toLowerCase'] ? key.toLowerCase() : key);
}
temp_array.push(key);
}
}
if (typeof type === 'function') {
temp_array.sort(type);
} else if (type === 'value') {
temp_array.sort(function(a,b) {
var x = obj[a];
var y = obj[b];
if (!caseSensitive) {
x = (x['toLowerCase'] ? x.toLowerCase() : x);
y = (y['toLowerCase'] ? y.toLowerCase() : y);
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
} else {
temp_array.sort();
}
var temp_obj = {};
for (var i=0; i<temp_array.length; i++) {
temp_obj[temp_array[i]] = obj[temp_array[i]];
}
return temp_obj;
};
And here are a couple of usage examples:
var obj = {c:'b',a:'c',b:'a'};
// Sort by key
sortObj(obj);
// {a:'c',b:'a',c:'b'}
// Sort by value
sortObj(obj, 'value');
// {b:'a',c:'b',a:'c'}
// Sort by predicate function
sortObj(obj, function(a,b) {
var data = {a:2,b:1,c:3};
var x = data[a];
var y = data[b];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
// {b:'a',a:'c':c:'a'}
If you want the sort to be case-sensitive, set the second parameter of .sort() to true.
As always when extending Object.prototype, don’t forget to use hasOwnProperty when iterating over the object. But you’re of course doing that already, right?
Update: Be careful using this with Chrome. If your object has both numbers and strings as keys, Chrome will sort the object with the number-keys first, even when sorting by value. Example:
var obj = {a:2, b:1, 1:'a'};
obj.sort('value'); // Other browsers: {b:1, a:2, 1:'a'}, Chrome: {1:'a', b:1, a:2}
My name is Arne Martin Aurlien. I run this thing. Here’s a few facts about me:
Here’s a few things I have made: