Skip to content

Instantly share code, notes, and snippets.

@loonywizard
Last active November 15, 2017 17:40
Show Gist options
  • Save loonywizard/2d526314ba554f196b34e17a43b82a01 to your computer and use it in GitHub Desktop.
Save loonywizard/2d526314ba554f196b34e17a43b82a01 to your computer and use it in GitHub Desktop.
This javascript function compares two objects by specific field, that function is helpful when you a sorting array of objects
/*
* Usage:
* const sortedArray = arrayOfObjects.sort((a, b) => compareTwoObjectsByField(a, b, 'fieldName'));
*/
export function compareTwoObjectsByField(a, b, field) {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment