I am trying to create a pipe that will sort an array of a custom type.
// custom-object.ts
export class CustomObject {
constructor(
public someString: string,
public someNumber: number
) {}
}
In my html is:
// custom-object-form.component.ts
<div class="form-group">
<label for="cricos_course_code">Object: </label>
<select class="form-control" required [(ngModel)]="model.someString">
<option *ngFor="#object of (customObjects | sortArrayOfCustomObjects)" [value]="object.someString">{{object.someString}}</option>
</select>
</div>
Then the code for the pipe:
// sort-custom-object.pipe.ts
import {Pipe, PipeTransform} from 'angular2/core';
import {CustomObject} from '../custom-object';
@Pipe({name: 'sortArrayOfCustomObjects'})
export class SortArrayOfCustomObjectsPipe implements PipeTransform {
transform(arr:Array<CustomObject>): any {
return arr.sort((a, b) => {
if (a.someString > b.someString) {
return 1;
}
if (a.someString < b.someString) {
return -1;
}
// a must be equal to b
return 0;
});
}
}
Now I am getting an error in the console:
EXCEPTION: TypeError: Cannot read property 'sort' of undefined in [(customObjects | sortArrayOfCustomObjects) in FormComponent@7:24]
Based off of your limited information I believe you want the following.
@Pipe({name: 'sortArrayOfCustomObjects'})
export class SortArrayOfCustomObjectsPipe implements PipeTransform {
transform(arr: CustomObject[], args: any): CustomObject[]{
return arr.sort((a, b) => {
if (a.p1 > b.p1 || a.p2 < b.p2) {
return 1;
}
if (a.p1 < b.p1 || a.p2 > b.p2) {
return -1;
}
return 0;
});
}
}
This will sort the objects first by p1, and then by p2. For instance.
{p1: 'AA', p2: 3},
{p1: 'CC', p2: 2},
{p1: 'BB', p2: 5},
{p1: 'BB', p2: 1},
{p1: 'AA', p2: 2},
{p1: 'DD', p2: 4}
Would be sorted to
{p1: 'AA', p2: 3},
{p1: 'AA', p2: 2},
{p1: 'BB', p2: 5},
{p1: 'BB', p2: 1},
{p1: 'CC', p2: 2},
{p1: 'DD', p2: 4}
This is based on your comment:
I have an array of objects that contain properties p1: string, p2: number etc. In my form I want to have 2 select fields that show a list of p1 in alphabetical order and p2 in descending order.
Usage would be
*ngFor="#item of (items | sortArrayOfCustomObjects)"
UPDATE
For your error that you are now receiving be sure to guard against undefined
values in arrays by using a guard.
transform(arr: CustomObject[], args: any): CustomObject[]{
if(!arr){ return; }
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With