Angular2 numeric orderBy pipe

1.1k Views Asked by At

I am trying to sort an array of strings by numerical value in Angular2 using a custom pipe (I did not write this pipe). Here is the pipe:

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

@Pipe( { name: 'numericalSort' } )

export class NumericalSortPipe implements PipeTransform {
transform( array: Array<any>, orderField: string, orderType: boolean ): Array<string> {
    array.sort( ( a: any, b: any ) => {
        let ae = a[ orderField ];
        let be = b[ orderField ];
        if ( ae == undefined && be == undefined ) return 0;
        if ( ae == undefined && be != undefined ) return orderType ? 1 : -1;
        if ( ae != undefined && be == undefined ) return orderType ? -1 : 1;
        if ( ae == be ) return 0;
        return orderType ? (ae.toString().toLowerCase() > be.toString().toLowerCase() ? -1 : 1) : (be.toString().toLowerCase() > ae.toString().toLowerCase() ? -1 : 1);
    } );
    return array;
  }
}

Here is the object. I need to be able to sort numerically by "label".

{
  "id" : "12345678",
  "accountId" : "123456789",
  "label" : "906",
  "fullAddress" : {
    "zip" : "12345"
  }
}

Here is sample HTML:

<div *ngFor="let place of places | numericalSort: 'label'">
  <h3>
    {{place.label}}
  </h3>
  ...
</div>

I am able to sort by the default alphabetical values. How can I sort by numerical value?

3

There are 3 best solutions below

0
On BEST ANSWER

I'd add a new parameter to the pipe that will indicate the real type of a field. So, the pipe will be able to cast string fields of items in your array to real types:

export class NumericalSortPipe implements PipeTransform {
    transform(array: Array<any>, orderField: string, orderType: boolean, dataType: string): Array<string> {
        array.sort((a: any, b: any) => {
            let ae = a[orderField];
            let be = b[orderField];
            if (ae === undefined && be === undefined) return 0;
            if (ae === undefined && be !== undefined) return orderType ? 1 : -1;
            if (ae !== undefined && be === undefined) return orderType ? -1 : 1;
            if (ae === be) return 0;
            switch (dataType) {
                case "number":
                    ae = parseFloat(ae);
                    be = parseFloat(be);
                    break;
                case "string":
                    ae = ae.toString().toLowerCase();
                    be = be.toString().toLowerCase();
                    break;

                default:
                    break;
            }
            return orderType ? (ae > be ? -1 : 1) : (be > ae ? -1 : 1);
        });
        return array;
    }
}

And usage:

<div *ngFor="let place of places | numericalSort: 'label':false:'number'">
    <h3>
        {{place.label}}
    </h3>
    {{place.id}}
</div>

See the plunk.

0
On

You can use lodash for sorting.

var myArray = [ 3, 4, 2, 9, 4, 2 ];

_.sortBy(myArray);
// → [ 2, 2, 3, 4, 4, 9 ]

_(myArray).sortBy().take(3).value();
// → [ 2, 2, 3 ]
0
On

Here is a pipe to order numerical first and then letters:

@Pipe({name: "orderBy", pure: false})
export class OrderByPipe implements PipeTransform {
  transform(array: Array<any>) {
    return array.sort((a, b) => {
        const [stringA, numberA] = this.order(a);
        const [stringB, numberB] = this.order(b);
        const comparison = stringA.localeCompare(stringB);
        return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
  })
  }

   order (item) {
      const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(\d*)$/.exec(item) || [];
  return [stringPart, numberPart];
  }
}

DEMO