自定义管道对数组的数组进行排序

Custom pipe to sort array of array

我有一个数组的数组,每个数组有两个元素,即 arr[a[2]]。索引 0 是名称,索引 1 是大小。我想要一个管道根据大小对数组的数组进行排序,即索引 1 .

示例:

arr [ [ 'hello' , '1' ] , [ 'how' , '5' ] , [ 'you' , '12' ] , [ 'are' , '6' ] ]

管道输出应为:

arr [ [ 'hello' , '1' ] , [ 'how' , '5' ] , [ 'are' , '6' ] , [ 'you' , '12' ] ]

HTML 文件:

<p> {{items  | custompipe }}</p>

使用管道进行排序不是一个好主意。请参阅此处的 link:https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

而是在组件中添加代码来执行排序。

这是一个例子。这是一个过滤器,但您可以将其更改为排序。

import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}