Search code examples
angulartypescriptsortingangular-pipe

Angular 4 OrderBy Pipe not sorting if name ends with number


I want to use pipe to sort names ending with numbers.

I have used custom pipe and getting results as expected

  • $Apple fruit -symbol
  • 1Apple fruit -numbers
  • Apple fruit -alphabetically

But it is not sorting if name ends with number.

Result now:

  • Apple fruit3
  • Apple fruit01
  • Apple fruit5
  • Apple fruit02

JSON

[
{"name": "Apple fruit3"},
{"name": "$Apple fruit"},
{"name": "Apple fruit"},
{"name": "Apple fruit01"},
{"name": "Apple fruit5"},
{"name": "Apple fruit02"},
]

HTML

<div *ngFor='let list of names | appOrderBy : "name" '>
<div>{{list.name}}</div>
</div>

OrderBy Custom Pipe

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

Solution

  • Use an Intl.Collator as your compare function for natural number sorting.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator

    const array = [
      {name: "Apple fruit3"},
      {name: "$Apple fruit"},
      {name: "Apple fruit"},
      {name: "Apple fruit01"},
      {name: "Apple fruit5"},
      {name: "Apple fruit02"},
    ];
    
    args= 'name';
    
    var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
    
    array.sort((a, b) => collator.compare(a[args], b[args]));
    
    console.log(array);

    I based this answer off searching for a natural number sort Google search which returned this post.

    Javascript : natural sort of alphanumerical strings