Skip to content

Instantly share code, notes, and snippets.

@73nko
Created August 22, 2018 06:09
Show Gist options
  • Save 73nko/7898c353d9403d1f00b69352801ef9b5 to your computer and use it in GitHub Desktop.
Save 73nko/7898c353d9403d1f00b69352801ef9b5 to your computer and use it in GitHub Desktop.
A function for array of objects sorting.
Array.prototype.sortBy = function(key, ascending = true) {
return this.sort((a, b) => {
if (ascending) {
return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
} else {
return a[key] > b[key] ? -1 : a[key] < b[key] ? 1 : 0;
}
});
};
var arr = [
{ name: "Kubar", age: 38, signedUpAt: new Date("April 3, 2008") },
{ name: "Rudy", age: 2, signedUpAt: new Date("May 25, 2018") },
{ name: "Okan", age: 37, signedUpAt: new Date("June 12, 1998") }
];
arr.sortBy("age",false);
arr.sortBy("name");
arr.sortBy("signedUpAt",false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment