Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created February 8, 2012 17:53
Show Gist options
  • Save ryanflorence/1771621 to your computer and use it in GitHub Desktop.
Save ryanflorence/1771621 to your computer and use it in GitHub Desktop.
Array.prototype.sortBy = (function() {
var sorters = {
string: function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
},
number: function(a, b) {
return a - b;
}
};
return function(prop) {
var type = typeof this[0][prop] || 'string';
return this.sort(function(a, b) {
return sorters[type](a[prop], b[prop]);
});
};
})();
var sortArrayByKey = (function() {
var sorters = {
string: function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
},
number: function(a, b) {
return a - b;
}
};
return function(ary, prop) {
var type = typeof ary[0][prop] || 'string';
return ary.sort(function(a, b) {
return sorters[type](a[prop], b[prop]);
});
};
})();
@ryanflorence
Copy link
Author

Also note, this only supports strings and numbers, but you could add more sorters inside the closure for other types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment