Sorting <li>s from the highest to lowest

Hello, I have problem to google ANYTHING helpfull about sorting lists.

I need

  • with the highest random number to be on the top of the list.

    Should i do it in template where I loop trough array of objects and list the products ? in controller ? I really dont know

    I can give you specifications if needed.

  • Hi @GuzlejM, there are a number of ways to sort the list. You could sort in the template or in javascript, and if you sort in javascript you would do that in the controller (if the list is rendered in a route template) or the component javascript (if the list is being rendered in a component template).

    To sort in the template you could use something like the sort-by helper in ember-composable-helpers.

    To sort in the controller or component js you could use the sort computed macro from @ember/object/computed or you could just write your own sort function.

    This is how I sort in JavaScript:

    function sort(items, property, direction = 1) {
      const comp = (a, z) => a?.localeCompare?.(z) ?? a - z;
      return items.sort((a, z) => (comp(a[prop], z[prop]) * direction);
    }
    

    But you mentioned li Suggesting this is to be used in a template. For me, I would use the sorting logic above in a provider component. If sorting were to be driven by query params I’d pass the query params to the provider component.

    <ThingsSorter @things={{this.model}} as |sortedThings|>
      <ul>
        {{#each sortedThings as |thing|}}
          <li>{{thing.foobar}}</li>
        {{/each}}
      </ul>
    </ThingsSorter>
    

    Hello every one thank you for your answers, I did it with

    model() { return this.store.findAll(‘venue’) .then(venue => venue.sortBy(‘votes’).reverse()); }

    1 Like

    Pedantic bike shed-ing

    async model() {
      let venue = await this.store.findAll('venue');
      return venue.sortBy('votes').reverse();
    }
    

    And to avoid an extra loop

    async model() {
      let venue = await this.store.findAll('venue');
      return venue.sort((a, z) => z.votes - a.votes);
    }