Last active
October 26, 2016 15:09
-
-
Save lahdo/af33a090e3d3f6f237562e94df8a62f0 to your computer and use it in GitHub Desktop.
Function which returns the objects ordered by age.
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
/** | |
* Orders users by age | |
* @param {Array} users - array of object where each one contains a name (a string) and age (a number) | |
* @return {Array} sorted_array_of_users | |
*/ | |
function order_by_age(users) { | |
var sorted_array_of_users = users.sort(compare("age", "ascending")); | |
return sorted_array_of_users; | |
} | |
/** | |
* Dynamic sort function that sorts objects by the given property name and the specified order | |
* @param {string} property | |
* @param {string} order - defualt is descending | |
* @return {function} compareFunction | |
*/ | |
function compare(property, order) { | |
var sortOrder = 1; | |
if(order === "ascending") { | |
sortOrder = -1; | |
} | |
return function (a,b) { | |
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; | |
return result * sortOrder; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment