Skip to content

Instantly share code, notes, and snippets.

@lukehedger
Created November 11, 2013 11:28
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 lukehedger/7411828 to your computer and use it in GitHub Desktop.
Save lukehedger/7411828 to your computer and use it in GitHub Desktop.
CoffeeScript Array.sort
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