Search code examples
javascriptangularjsangularjs-orderby

AngularJS custom sort


If I have an array of values:

[1, 2, 3, 4, n/a, n/a, n/a]

How do I create a custom sort with orderBy so that the strings always appear at the bottom?

ascending example:

[1, 2, 3, 4, n/a, n/a, n/a]

descending example:

[4, 3, 2, 1, n/a, n/a, n/a]

I've tried using the function expression but that doesn't do what I need. the function expression only returns the value to be sorted but how do I use my own sort order?


Solution

  • You can create a custom filter that would sort your array as you need it.

    app.filter('customOrderBy', function () {
       return function (arr) {
    
         var numbers = [];
         var strings = [];
    
           angular.forEach(arr, function(item){
                if(typeof item == 'number' ){
                  numbers.push(item);     
                }
                else
                  strings.push(item);     
              });
    
            return numbers.sort().concat(strings);
        };
    });
    

    Your ng-repeat on your array would look like below:

      <div ng-repeat="item in array | customOrderBy track by $index">
    

    Note that I have used 'track by $index' there because AngularJS ng-repeat directive does not allow duplicates in the repeater. (You had duplicate "n/a" strings in your array)

    Plunker here sorts in ascending order the numbers in an original array of [2, 3, 1, 4, 'n/a', 'n/a', 'n/a']: http://plnkr.co/edit/jmHly0lDb5IVeWd2XvHp?p=preview