Skip to content

Instantly share code, notes, and snippets.

@lahdo
Last active October 26, 2016 15:09
Show Gist options
  • Save lahdo/af33a090e3d3f6f237562e94df8a62f0 to your computer and use it in GitHub Desktop.
Save lahdo/af33a090e3d3f6f237562e94df8a62f0 to your computer and use it in GitHub Desktop.
Function which returns the objects ordered by age.
/**
* 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