Issue
I set up pipeline for sorting. It is sorting but I got this type of error:
cannot read properties of undefined (reading 'sort')
in angular core.js in my local running.
Here is my order-by.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy',
})
export class OrderByPipe implements PipeTransform {
transform(array: any, field: string): any[] {
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}
Solution
You need to check that array
must have value then only proceed for sorting.
Meanwhile, you should specify array
as any[]
type as sort()
is a method provided by Array
.
Solution 1
Straight break the function when array
is nullish (null
or undefined
).
transform(array: any[], field: string): any[] {
if (!array) return array;
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
Sample Solution 1 on StackBlitz
Solution 2
Use Typescript optional chaining so that .sort()
will not be executed when array
is nullish (null
or undefined
).
transform(array: any[], field: string): any[] {
array?.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
Sample Solution 2 on StackBlitz
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.