Created
March 27, 2012 08:27
-
-
Save JoeChapman/2213994 to your computer and use it in GitHub Desktop.
Sorting an array of objects by key
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
| var arr = [ | |
| {first: 'Joseph', last: 'Smith'}, | |
| {first: 'Joseph', last: 'Chapman'}, | |
| {first: 'Joseph', last: 'Hinge'} | |
| ]; | |
| var sortBy = function (key) { | |
| return function (o, p) { | |
| var a, b; | |
| if (o && p && typeof o === 'object' && typeof p === 'object') { | |
| a = o[key]; | |
| b = p[key]; | |
| if (a === b) { | |
| return 0; | |
| } | |
| if (typeof a === typeof b) { | |
| return a < b ? -1 : 1; | |
| } | |
| return typeof a < typeof b ? -1 : 1; | |
| } | |
| } | |
| }; | |
| arr.sort(sortBy('last')); | |
| // arr is [{first: 'Joseph', last: 'Chapman'}, {first: 'Joseph', last: 'Hinge'}, {first: 'Joseph', last: 'Smith'}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment