0

Angular 4 - how to sort version number string in an array using custom pipe?

I have a json file with version number like v.9.1, v.9.2, v10.0. I tried sorting using custom pipe but sorted as v.9.2, v.9.1, v.10.0 rather than v.10.0, v.9.2, v.9.1. So it looks like it's been treated as string.

Here is what I have tried in the pipe:

import {Injectable, PipeTransform, Pipe} from '@angular/core';
import { P11dComponent } from './p11d.component';

@Pipe({
    name: 'sortByVersion'
})

@Injectable()
export class SortVersionPipe implements PipeTransform{

transform(array: Array<any>, args: string): Array<any> {
        if (array !== undefined) {

            array.sort((a: any, b: any) => {
                if ( parseFloat(a[args.slice(3,4)]) < parseFloat(b[args.slice(3.4)]) ){
                    return 1;
                } else if ( parseFloat(a[args.slice(3,4)]) < parseFloat(b[args.slice(3.4)]) ) {
                    return -1;
                } else {
                    return 0;   
                }
            });
        }
        return array;
}
}
Vega
  • 27,856
  • 27
  • 95
  • 103
far007ial
  • 33
  • 4

1 Answers1

1

If we have array like:

arr = ['v.9.1', 'v.9.2', 'v.10.0']

then transform method could look like:

transform(array: Array<any>): Array<any> {
    if(!array) {
      return null;
    }
    return array.sort((a, b) => b.slice(2) - a.slice(2));
}

Plunker Example

Just a note: you do not need to use @Injectable for classes that has already adorned @Component, @NgModule, @Directive or @Pipe decorator.

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Sorry, it didn't work in my code. I am extracting data from a json file which is like this - – far007ial Aug 19 '17 at 19:17
  • @farialmahmud I added json file to my example https://plnkr.co/edit/zqpkih1AaRAgySyklOrZ?p=preview Can you reproduce it there? – yurzui Aug 19 '17 at 19:22
  • [ { "version" : "v.9.1", "date" : "08/11/2016", "link": "9-1/setup.zip" }, { "version" : "v.9.0", "date" : "05/08/2016", "link": "9-0/setup.zip" }, { "version" : "v8.1", "date" : "02/11/2015", "link": "8-1/setup.zip" }, { "version" : "v9.2", "date" : "20/03/2017", "link": "9-2/setup.zip" }, { "version" : "v10.0", "date" : "20/03/2017", "link": "10.0/setup.zip" } ] – far007ial Aug 19 '17 at 19:31
  • I am getting this data in a component through an Interface - export interface iSometLinks { version:string; date: Date; link: string; } Used ngFor to view this like below {{someLink.version}} – far007ial Aug 19 '17 at 19:33
  • i also needed to sort version numbers like v4.0.0.10, v4.0.0.15, v4.0.0.40 etc. which i sorted like below. Posting as someone may find it useful. export class SortVerPipe implements PipeTransform{ transform(array: Array, args: string): Array { if (array !== undefined) { array.sort((a: any, b: any) => { if ( a.version < b.version ){ return 1; } else if ( a.version > b.verision ) { return -1; } else { return 0; } }); } return array; } } – far007ial Aug 20 '17 at 20:22