Search code examples
angularangular6angular-pipe

To filter Json data in alphabetical order in angular 6


This is my (customet.component.html) file

    <input type="text" [(ngModel)]="name" (ngModelChange)="onNameChange()">

      <div *ngFor="let s of filteredScreenshots">
           {{s | json}}
        </div>

      <mat-card class="example-card" *ngFor="let filteredScreen  of 
         filteredScreens ; let i = index">
          <mat-card-header>
           <div mat-card-avatar class="example-header-image" >
               <img mat-card-image class="list-img" src=" 
              {{filteredScreen?.img}}" >
           </div>
        <mat-card-content class="names">{{ filteredScreen?.name }}</mat-card- 
          content>
         </mat-card-header>
     </mat-card>

This is(customer.component.ts)file

            import { Component, OnInit } from '@angular/core';
            import { Http } from '@angular/http'; 
            import { map } from 'rxjs/operators'
            import * as _ from 'lodash';

            @Component({
            selector: 'ylb-customer',
            templateUrl: './customer.component.html',
            styleUrls: ['./customer.component.css']
            })

            export class CustomerComponent  {

            spaceScreens: Array<any>;
            filteredScreens = [];
            name: string;

            constructor(private http:Http){
                this.http.get('assets/app.json').pipe(
                        map(response => response.json().screenshots)
                    )
                    .subscribe(res => {
                        this.spaceScreens = res; 
                        this.filteredScreens = res;
                });
            }

            onNameChange() {
                this.filteredScreens = _.filter(this.spaceScreens, (screenshot) => {
                    const name = screenshot['name'];
                    const filteredName = this.name.toUpperCase();
                    return name === undefined ? false : name.toUpperCase().startsWith(filteredName);
                });
            }



            }

this json file present inside assets folder(app.json)

              {   
        "screenshots":[ 

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Ramesh Kumar"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Joe Root"
                    },

                    {
                        "img":"assets/img/json_2.jpg",
                        "name":"Adam Evans"
                    }



            ]        
        }

Search/filter is working fine,How can i make the data present in json file to display in alphabetical order and How can i apply search for last name of the name string,i mean suppose i want to search chris woakes,how can i search it by typing only woakes.


Solution

  • I took bajaran's answer and modified it to not fail when the content of a field is null and to work case insensitively:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
        name: 'sort'
    })
    export class SortPipe implements PipeTransform {
    
        transform(array: any, field: string): any[] {
            if (!array) {
                return array;
            }
            array.sort((a: any, b: any) => {
                if ((a[field] || '').toLowerCase() < (b[field] || '').toLowerCase()) {
                    return -1;
                } else if ((a[field] || '').toLowerCase() > (b[field] || '').toLowerCase()) {
                    return 1;
                } else {
                    return 0;
                }
            });
            return array;
        }
    }