Search code examples
sortingember.jsember-data

How to sort an array values in `desc` in computed?


I have an model value, when i do the each iteration it works fine.

<ul>
    <li>See here : </li>
    {{#each selectedCreditCard.balances.tenures as |balance|}}
    <li>Balances is : {{balance}}</li>
    {{/each}}
</ul>

But I require to sorted the value by desc way. so I use the computed method to do the desc the array.

sortTenuresBy:['desc'],
sortedTenures: Ember.computed.sort('selectedCreditCard.balances.tenures', 'sortTenuresBy'),
maxTenure:Ember.computed(function(){
return this.get('sortedTenures').get('firstObject');

But getting error as like this:

Assertion Failed: When using @each to observe the array 3,8,12,24, the array must return an object

how to fix this? please help me


Solution

  • If you look at API definition for Ember.computed.sort; it requires a property key (that is selectedCreditCard.balances.tenures in your case) and a sort definition (that is sortTenuresBy in your case). However, if you look at the examples provided; the sort definition must be either a plain property name or a property name followed by sort type such as name:desc or key:asc and so on. In summary; it is not possible to use Ember.computed.sort for plain arrays as in your case. I admit the API documentation is vague.

    For your case; you have to either write the computed property as a function; which is what you do not want I suppose; because it is the common way; or you can make use of the following addon. What is great about ember-awesome-macros is you can nest the provided computed macros.

    If you look at API for array.sort; it says "combines the functionality of both Array.prototype.sort() and Ember.computed.sort". Hence we can use this one. You want the array to be sorted in descending; I suppose something like the following

    sortTenuresBy: array.reverse(array.sort('selectedCreditCard.balances.tenures'))
    

    should work.