Order a list


#1

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?


#2

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>

#3

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.


#4

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


#5

What if you wanted to sort by date?


#6

Wouldn’t you just send in the date value as the arg?