angularsortingangular2-custom-pipes

How to sort version number in Angular 2 custom pipe?


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

Solution

  • 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.