Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of EmberJS objects by property

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

like image 950
skinneejoe Avatar asked Jan 27 '12 23:01

skinneejoe


People also ask

How do you sort an array of objects based on property?

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.

Can we sort array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort a list of objects based on an attribute of the objects in JavaScript?

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.


2 Answers

Ember MutableArray has a sortBy method:

https://emberjs.com/api/ember/release/classes/MutableArray

like image 183
Nath Avatar answered Sep 21 '22 03:09

Nath


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'}
like image 23
Willem de Wit Avatar answered Sep 24 '22 03:09

Willem de Wit