I noticed this on the EmberJS website under Filtering:
Another common task to perform on an Enumerable is to take the Enumerable as input, and return an Array after sorting or filtering it based on some criteria.
Imagine I have an array of Ember objects, how do I go about sorting them by property?
App.DemoArray = Ember.ArrayController.create({
content:[
Ember.Object.create({name:'Joe', Age:29}),
Ember.Object.create({name:'Jim', Age:53}),
Ember.Object.create({name:'Jack', Age:12})
]
})
What if I wanted to sort the above by age? Thanks for your help!
EDIT: I found this in the sproutcore documentation but it doesn't seem to work with Ember:
You can sort an Enumerable based on the value of some property or list of properties using sortProperty. If you pass in multiple properties, SproutCore will sort items with the same value for the first property by the value of the second parameter, and so on.
Section 3.8 on this page: http://guides.sproutcore20.com/enumerables.html
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.
Ember MutableArray
has a sortBy
method:
https://emberjs.com/api/ember/release/classes/MutableArray
As described here you can now sort your ArrayController.
The way you do it is provide extra properties on your ArrayController (pasted from link above):
songs = [
{trackNumber: 4, title: 'Ob-La-Di, Ob-La-Da'},
{trackNumber: 2, title: 'Back in the U.S.S.R.'},
{trackNumber: 3, title: 'Glass Onion'},
];
songsController = Ember.ArrayController.create({
content: songs,
sortProperties: ['trackNumber'],
sortAscending: true
});
songsController.get('firstObject'); // {trackNumber: 2, title: 'Back in the U.S.S.R.'}
songsController.addObject({trackNumber: 1, title: 'Dear Prudence'});
songsController.get('firstObject'); // {trackNumber: 1, title: 'Dear Prudence'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With