SortPipe
Create a sort.pipe.ts and replace with the following code:
import { Injectable, Pipe, PipeTransform } from '@angular/core';
export type SortOrder = 'asc' | 'desc';
@Injectable()
@Pipe({
name: 'sort',
})
export class SortPipe implements PipeTransform {
transform(value: any[], sortOrder: SortOrder | string = 'asc', sortKey?: string): any {
sortOrder = sortOrder && (sortOrder.toLowerCase() as any);
if (!value || (sortOrder !== 'asc' && sortOrder !== 'desc')) return value;
let numberArray = [];
let stringArray = [];
if (!sortKey) {
numberArray = value.filter(item => typeof item === 'number').sort();
stringArray = value.filter(item => typeof item === 'string').sort();
} else {
numberArray = value.filter(item => typeof item[sortKey] === 'number').sort((a, b) => a[sortKey] - b[sortKey]);
stringArray = value
.filter(item => typeof item[sortKey] === 'string')
.sort((a, b) => {
if (a[sortKey] < b[sortKey]) return -1;
else if (a[sortKey] > b[sortKey]) return 1;
else return 0;
});
}
const sorted = [
...numberArray,
...stringArray,
...value.filter(
item =>
typeof (sortKey ? item[sortKey] : item) !== 'number' &&
typeof (sortKey ? item[sortKey] : item) !== 'string',
),
];
return sortOrder === 'asc' ? sorted : sorted.reverse();
}
}
Then, you must add this pipe into declarations of a module. You can add the AppModule like below:
import { SortPipe } from './shared/pipes/sort.pipe';
@NgModule({
declarations: [/* ... */, SortPipe],
providers: [/* ... */, SortPipe],
})
export class AppModule { }
How to use?
In HTML:
<div *ngFor="let myObj of myArr | sort:'asc':'name'">{{ myObj | json }}</div>
In Component:
import { Component } from "@angular/core";
import { SortPipe } from "./shared/pipes/sort.pipe";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
myArr = [
{ name: "G", sex: "F", age: 15 },
{ name: "B", sex: "M", age: 25 },
{ name: "Z", sex: "F", age: 18 },
{ name: "A", sex: "F", age: 12 },
{ name: "H", sex: "M", age: 19 }
];
constructor(private sortPipe: SortPipe) {}
ngOnInit() {
const myArr = [
{ name: "G", sex: "F", age: 15 },
{ name: "B", sex: "M", age: 25 },
{ name: "Z", sex: "F", age: 18 },
{ name: "A", sex: "F", age: 12 },
{ name: "H", sex: "M", age: 19 }
];
const sortedArr = this.sortPipe.transform(myArr, "desc", "name");
console.log(sortedArr);
// Output: [{"name":"Z","sex":"F","age":18},
{"name":"H","sex":"M","age":19},
{"name":"G","sex":"F","age":15},
{"name":"B","sex":"M","age":25},
{"name":"A","sex":"F","age":12}]
}
}
See the Stackblitz example:
https://stackblitz.com/edit/angular-sort-pipe