Search code examples
angularjsangularjs-filter

Angularjs filter orderby numbers and alphabets


I want to order by 'displayName'. Sometimes displayName has all numbers or alphabets. $filter('orderBy') is working fine for alphabets. But numbers are rendering like this.

1,13,2,23,3,43. 

How can I filter for numbers and alphabets?

    vm.temp=[{id:15, displayName:'ff'},
    {id:2, displayName:'f'},
    {id:10, displayName:'cc'},
    {id:3, displayName:'aa'},
    {id:5, displayName:'h'},
    {id:8, displayName:'y'}]
OR
   vm.temp=[{id:15, displayName:'3'},
    {id:2, displayName:'2'},
    {id:3, displayName:'43'},
    {id:5, displayName:'13'},
    {id:8, displayName:'1'},
 {id:9, displayName:'23'}]

    vm.items = $filter('orderBy')(vm.temp, 'displayName');

Solution

  • Add the sorter function:

    function sorter(a) {
      if(isNaN(parseInt(a.displayName))) {
        return a.displayName;
      }
      else {
        return parseInt(a.displayName);
      }
    }
    

    Update the last line of your code with this:

    vm.items = $filter('orderBy')(vm.temp, sorter);
    

    Demo: https://plnkr.co/edit/OfNpqSv3Pj9CDD3bMyoQ?p=streamer