Skip to content

Instantly share code, notes, and snippets.

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 RohitRox/9691567 to your computer and use it in GitHub Desktop.
Save RohitRox/9691567 to your computer and use it in GitHub Desktop.
# Sorts an array based on a property of each object within the array
#
# Examples:
#
# [Em.Object.create(a: 1), Em.Object.create(a: 5), Em.Object.create(a: 3)].sortProperty('a')
# > [{a: 1}, {a: 3}, {a: 5}]
#
# As a computed property:
#
# AC = Em.ArrayController.extend
# content: [Em.Object.create(a: 1), Em.Object.create(a: 5), Em.Object.create(a: 3)]
# sorted: (-> @content.sortProperty('a')).property('content.@each.a')
Array::sortProperty = (property, order = 'DESC') ->
if order == 'DESC'
return @sort (a, b) =>
if a.get(property) > b.get(property) then 1
else if a.get(property) < b.get(property) then -1
else 0
else if order == 'ASC'
return @sort (a, b) =>
if a.get(property) < b.get(property) then 1
else if a.get(property) > b.get(property) then -1
else 0
else throw new Error('Sort order must be DESC or ASC.')
Array::maxObject = (property) ->
max = @objectAt(0)
@forEach (o) -> max = o if o.get(property) > max.get(property)
return max
Array::maxValue = (property) ->
@maxObject(property).get(property)
Array::minObject = (property) ->
min = @objectAt(0)
@forEach (o) -> min = o if o.get(property) < min.get(property)
return min
Array::minValue = (property) ->
@minObject(property).get(property)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment