Last active
November 15, 2017 17:40
-
-
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
This file contains hidden or 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
/* | |
* 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