0

I have created a custom pipe to sort the array of objects but the pipe is not working ? my array of [ {name , population , variable }] . i want to sort the array of object according to population

PIPE:

import {Pipe , PipeTransform } from '@angular/core';

     @Pipe ({
    name:'order'
    })

    export class OrderByPipe implements PipeTransform{
    transform(value: any[], property: any, descending?: boolean): any {
    if (!value || value.length) {
      return value;
    }

    value.sort((first: any, second: any): number => {
        return first[property] > second[property] ? 1 : -1;
    });

    if (descending) {
      return value.reverse();
    }

    return value;
  }
} 

HTML:

 <ul>
 <li *ngFor="let items of results"
   {{items.name | order:'population':'true'  }}
</li>
</ul>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
Tarik Sahni
  • 158
  • 1
  • 2
  • 13
  • This kind of question has been asked a lot... For example..https://stackoverflow.com/questions/35461203/angular-2-how-to-apply-orderby/35479995#35479995 Also it's not a best practise. Use services... See here https://angular.io/guide/pipes#no-filter-pipe – JGFMK Jul 20 '17 at 20:45

3 Answers3

0

You are passing items.name to the pipe.

This is a string not having a property population.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

You should have like this

<li *ngFor="let items of results | order:'population':'true'">
   {{items.name}}
</li>

Also your Pipe has a problem you need to check the length of array as 0, otherwise it will always return the same array without sorting

 if (!value || value.length == 0) {
      return value;
 }

DEMO

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • can you post the json – Sajeetharan Jul 20 '17 at 19:16
  • results is array of objects and i want to sort the array according to population property of object . – Tarik Sahni Jul 20 '17 at 19:19
  • which json are you telling about – Tarik Sahni Jul 20 '17 at 19:19