Skip to content

Instantly share code, notes, and snippets.

@phunanon
Forked from ryanflorence/Array.prototype.sortBy.js
Last active March 18, 2021 17:40
Show Gist options
  • Save phunanon/f43b628584855d3c1cc74e2de5bc968a to your computer and use it in GitHub Desktop.
Save phunanon/f43b628584855d3c1cc74e2de5bc968a to your computer and use it in GitHub Desktop.
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]));
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment