Custom pipe to sort array of array

为君一笑 提交于 2019-12-31 07:03:47

问题


I have a array of array having two elements each, i.e. arr[a[2]]. Index 0 is name and index 1 is size . I want a pipe to sort the array of array according to size ie index 1 .

Example:

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

Output of pipe should be :

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

HTML file:

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

回答1:


It's not a good idea to use a pipe for sorting. See the link here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

Rather, add code in your component to perform your sort.

Here is an example. This one filters, but you could change it to sort instead.

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);
    }
}


来源:https://stackoverflow.com/questions/45199776/custom-pipe-to-sort-array-of-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!