How to sort objects in ember.js?

Member

by larissa , in category: Javascript , a month ago

How to sort objects in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , a month ago

@larissa 

In Ember.js, you can sort objects by using the sort() method provided by Ember. Here's an example of how you can sort objects in Ember.js:

1
2
3
4
5
6
7
8
9
// Controller
import Controller from '@ember/controller';
import { computed } from '@ember/object';

export default Controller.extend({
  sortedObjects: computed('model', function() {
    return this.get('model').sortBy('propertyNameToSortBy');
  })
});


In this example, we have a controller that has a computed property called sortedObjects. This property depends on the model and will return a sorted array of objects based on the specified property name propertyNameToSortBy.


You can then use {{#each}} in your template to display the sorted objects:

1
2
3
{{#each sortedObjects as |object|}}
  <p>{{object.propertyNameToDisplay}}</p>
{{/each}}


This will display the objects sorted based on the specified property name in your template.