Angular Sorting with null objects

前端 未结 4 1175
耶瑟儿~
耶瑟儿~ 2020-12-21 05:39

I need to take records with null values on top , when I\'m sorting by ASC



        
4条回答
  •  一整个雨季
    2020-12-21 06:32

    I was able to do it by returning a '+' or a '-' if the value is null, close to what bmleite did but is more contained in the function itself.

    1. create a function that adds a + or a - to the null values depending on the sort order (asc or desc) so that they'd always remain at either the top or bottom

        function compareAndExcludeNull(element){
            var compareWith = $scope.order.propertyName; // in your case that's 'predicate'
    
            var operatorToBottom = $scope.order.reverse ? '+' : '-'; // If decending then consider the null values as smallest, if ascending then consider them biggest
            var operatorToTop = $scope.order.reverse ? '-' : '+';
    
            if(element[compareWith] == null){
                return operatorToTop;
            } else {
                return operatorToBottom+element[compareWith];
            }
        }
    

    if you want to have the null values at the bottom of the sorted array then just switch the operatorToTop with operatorToBottom and vice versa to get:

        function compareAndExcludeNull(element){
            var compareWith = $scope.order.propertyName; // in your case that's '
    
            var operatorToBottom = $scope.order.reverse ? '+' : '-'; // If decending then consider the null values as smallest, if ascending then consider them biggest
            var operatorToTop = $scope.order.reverse ? '-' : '+';
    
            if(element[compareWith] == null){
                return operatorToBottom;
            } else {
                return operatorToTop+element[compareWith];
            }
        }
    

    2. Call the function and pass the array you're sorting

    Javascript:

    In my case I am calling this function from HTML and passing different propertyName depending on the column the user is sorting by, in your case you'd just need to pass 'predicate' as the propertyName

        $scope.order.sortBy = function(propertyName){
            $scope.order.reverse = (propertyName !== null && $scope.order.propertyName === propertyName) ? !$scope.order.reverse : false;
            $scope.order.propertyName = propertyName;
            $scope.resources = $filter('orderBy')($scope.resources,compareAndExcludeNull,$scope.order.reverse);
        };
    

    HTML:

    Order by Keywords Order by Website

提交回复
热议问题