Created
August 22, 2018 06:09
-
-
Save 73nko/7898c353d9403d1f00b69352801ef9b5 to your computer and use it in GitHub Desktop.
A function for array of objects sorting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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