Sort array of EmberJS objects by property
-
03-12-2019 - |
Question
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
La solution
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'}
Autres conseils
Ember MutableArray
has a sortBy
method:
EDIT: The below solution seems to only apply to numeric values. However this link will give advice on how to handle alpha-numeric, dates, etc: http://www.javascriptkit.com/javatutors/arraysort2.shtml
Nevermind, I figured it out. You can do it with Javascripts built in sort method:
//To sort ASC
var sorted = content.sort(function(a,b) {
return a.get('propertyYouWantToSortBy') - b.get('propertyYouWantToSortBy');
});
//To sort DESC
var sorted = content.sort(function(a,b) {
return b.get('propertyYouWantToSortBy') - a.get('propertyYouWantToSortBy');
});
in case anybody comes across this, the updated way to sort in ember is
Ember.computed.sort('nameOfArrayToSort', sortDefinition)
sortDefinition may be an array of strings
['mainSortProperty:asc', 'secondarySortProp:desc', ...]
or a comparator function
docs here: http://emberjs.com/api/classes/Ember.computed.html#method_sort
As discussed in https://github.com/emberjs/ember.js/issues/335 sorting is not implemented anymore in the core ember.js
package.