To sort an array you use Array.sort
with an appropriate comparison function as an argument. The comparison function accepts two arguments, which in this case are expected to be objects with just a single property. You want to sort based on the name of that property.
Getting an object's property names is most convenient with Object.keys
, so we have this comparison function:
function(x, y) {
var keyX = Object.keys(x)[0],
keyY = Object.keys(y)[0];
if (keyX == keyY) return 0;
return keyX < keyY ? -1 : 1;
}
It can be used like this:
var input = [{ d: "delete the text" }, { c: "copy the text" } ];
var sorted = input.sort(function(x, y) {
var keyX = Object.keys(x)[0],
keyY = Object.keys(y)[0];
if (keyX == keyY) return 0;
return keyX < keyY ? -1 : 1;
});
See it in action.
Note that Object.keys
requires a reasonably modern browser (in particular, IE version at least 9); otherwise you would need to write something such as this instead:
var keyX, keyY, name;
for (name in x) { keyX = name; break; }
for (name in y) { keyY = name; break; }
See it in action.