Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'sort' of undefined at SortPipe.transform ,Why?

I have created one pipe to sort the array, but when I use the pipe to sort it says error :

Error: Uncaught (in promise): TypeError: Cannot read property 'sort' of undefined.

pipe.ts

import { Component, NgModule, Pipe, PipeTransform } from '@angular/core';

@Pipe({name: "sortBy"})
export class SortPipe {
    transform(array: Array<string>, args: string): Array<string> {
        array.sort((a: any, b: any) => {
            if (a[args] < b[args]) {
                return -1;
            } else if (a[args] > b[args]) {
                return 1;
            } else {
                return 0;
            }
        });
        return array;
    }
}

I have included the SortPipe in declarations and providers of @NgModule.

pipe.html

<ion-item item-detail *ngFor="let exhibit of exhibits | sortBy : 'name' 
        let i = index" name="exhibit">
    <h2>{{ exhibit?.name }}</h2>
    <h5>{{ exhibit.plan }}</h5>
    <h5>{{ exhibit.link }}</h5>
    <h5>{{ exhibit.stall }}</h5>
    <h5>{{ exhibit.description }}</h5>
</ion-item>
like image 727
Ajith Avatar asked Jul 19 '17 06:07

Ajith


1 Answers

Try wrapping your pipe code in an if statement that checks to determine if array is undefined, like so:

import { Component, NgModule, Pipe,PipeTransform } from '@angular/core';

    @Pipe({ name: "sortBy" })

    export class SortPipe {

    transform(array: Array<string>, args: string): Array<string> {
        if (array !== undefined) {
            array.sort((a: any, b: any) => {
                if ( a[args] < b[args] ){
                    return -1;
                } else if ( a[args] > b[args] ) {
                    return 1;
                } else {
                    return 0;   
                }
            });
        }
        return array;
    }
like image 122
LarsMonty Avatar answered Oct 21 '22 18:10

LarsMonty