Skip to content

Instantly share code, notes, and snippets.

Array.prototype.sortBy = (function() {
const sorters = {
string: (a, b) => a < b ? -1 : (a > b ? 1 : 0),
number: (a, b) => a - b,
};
return function(prop) {
const type = typeof this[0][prop] || 'string';
return this.sort((a, b) => sorters[type](a[prop], b[prop]));
};
})();