Order a list

Hi!

I have a page with a list and I want to order the list items. I tried it with the javascript function sort() to sort the array in the .ts file, but that didnt work. Here is my code:

.html:

...
<ion-content padding class="categories">
    <ion-list>
        <ion-item *ngFor="let category of categories">
            {{category}}
        </ion-item>
    </ion-list>
</ion-content>

.ts:

...
categories: Array<any>;

constructor(private nav: NavController, public listService: ListService) {

    this.loadCategories();

    this.categories.sort();

}

loadCategories() {
    
    var categories = [];

    this.listService.load()
        .then(data => {

            data.forEach(function (list) {

                if (categories.indexOf(list.category) == -1) { // Every category only one time

                    categories.push(list.category);

                }

            });
            
        });

    this.categories = categories;

}

The list service gives me an extern json file and I store for every json object the ā€œcategoryā€ value. And every category should be an item of the list. And I want to sort them. What can I do?

1 Like

For something like this, Iā€™d use a pipe to order the element.

import {Injectable, Pipe} from 'angular2/core';
import * as _ from 'lodash';

@Pipe({ name: 'order-by' })
export class OrderByPipe {
  transform(array, args) {
    return _.sortBy(array, args);
  }
}

then you could use it like

<a ion-item *ngFor="#item of items | order-by:'value'">{{item.value</a>
6 Likes

Be cool if thereā€™s an Ionic way to do it. I read that Angular 2 donā€™t want to have it as a feature because wanting to be minified. Does that apply to Ionic 2? If not, itā€™d be a very nice feature.

If someone has a problem with his code, check out this question

What if you wanted to sort by date?

4 Likes

Wouldnā€™t you just send in the date value as the arg?