Skip to content

Instantly share code, notes, and snippets.

@akhsiM
Last active March 2, 2021 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akhsiM/1232fa673acdf5a7398ba0ab4d6e13b9 to your computer and use it in GitHub Desktop.
Save akhsiM/1232fa673acdf5a7398ba0ab4d6e13b9 to your computer and use it in GitHub Desktop.
/*
In JS the array.sort() function can take a COMPARE function as an argument argument. The purpose of this function is to define an alternative order.
This is useful in cases where we need to sort an array of JS objects, using a key attribute, such as "ordering".
Example:
function(a, b) {
return a - b
}
- If the return is negative, index of a will be smaller than b, i.e a will be sorted before b.
- If the return is positve, index of a will be greater than b, i.e a will be sorted after b.
- If the return i 0, no changes are done to index of a and b.
For example, when we call something like:
[100, 50].sort()
This is what's really happening: [100, 50].sort(function (100 , 50) {return 100 - 50}). Because the result is postive, 100 is sorted after 50.
Use the following compare function to sort an array of JS objects, passing the sorting attribute or key as an argument.
*/
function compare(prop) {
return function (a, b) {
if (a[prop] > b[prop]) {
return 1;
} else if (a[prop] < b[prop]) {
return -1;
}
return 0;
};
}
// if sorting attribute is numerical
function compare(sorting_attribute) {
return function (a, b) {
return a[sorting_attribute] - b[sorting_attribute];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment