ember.jsember-model

How to sort the model array before supply to template


Here is my model, how can i sort it before I send to template?

route.js

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return {
            "fruits":[
            {fruit:"mango",color:"yello"},
            {fruit:"banana",color:"muddy yellow"},
            {fruit:"apple",color:"red"}],
          "prices":[9, 10,5 ]
                }
   } 
});

Twiddle Demo

Any one please update my twiddle? looking for ember approch.

here is my hbs:

<h1>Fruit Prices Sorted here</h1> 
<ul>
{{#each sortedSongs as |price|}}
    <li> {{price.fruit}}</li>
{{/each}}
</ul>

<h1>Fruit Prices Sorted here</h1> 
<ul>
{{#each sortedPrice as |price|}}
    <li> {{price.price}}</li>
{{/each}}
</ul>

<h1>Fruit Details Sorted by Alphabetically </h1> 
<ul>
{{#each model.fruits as |fruitObject|}}
    <li> {{fruitObject.fruit}}</li>
{{/each}}
</ul>
<br>
<h1>Fruit Color Sorted by Alphabetically </h1> 
<ul>
{{#each model.fruits as |fruitObject|}}
    <li> {{fruitObject.color}}</li>
{{/each}}
</ul>

Solution

  • Take a look into Ember.computed.sort or

    In your twiddle you should create a computed property in the controller, which would sort model.fruits and return the result, e.g.:

    nameSort: ['name'],
    sortedByName: Ember.computed.sort('model.fruits', 'nameSort')
    

    The second argument has to be a name of a property which holds an array of properties you want to sort by. Or you can provide a function if you need some custom sorting logic.

    I've edited your twiddle. Also I think the price attribute was supposed to go inside each fruit object, not in a separate list, so I moved it.

    https://ember-twiddle.com/78e0b3e9ff873a8909221efc87e3ef43

    Next time do some research though, Ember.computed.sort documentation isn't hard to find.