Created
November 11, 2013 11:28
-
-
Save lukehedger/7411828 to your computer and use it in GitHub Desktop.
CoffeeScript Array.sort
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
array = [ | |
{ | |
"id":"1", | |
"type":"z" | |
}, | |
{ | |
"id":"2", | |
"type":"a" | |
} | |
] | |
sorted = array.sort(@sorter) | |
# this callback function will sort strings | |
sorter: (a,b) -> | |
if a.type > b.type | |
return 1 | |
else if a.type < b.type | |
return -1 | |
else | |
return 0 | |
# sorted = [{"id":"2","type":"a"},{"id":"1","type":"z"}] | |
# to sort numbers instead of strings the callback function simply becomes: | |
sorter: (a,b) -> | |
return a.id - b.id | |
# sorted = [{"id":"1","type":"z"},{"id":"2","type":"a"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment