sioesi sioesi - 2 months ago 11
AngularJS Question

ng-repeat order by number only positive value

I have a list I want to sort based on a number. This number can be negative or positive. My idea is that the order of lowest to highest, but the number must be positive, negative automatically hidden. But I want to add an option, such as a selector that says only positive or All. If you select all showing both negative and positive but negative to the last. Whereas if I select only positive, show positive from lowest to highest. It could do this?

<ion-item ng-repeat="torneo in torneos | orderObjectBy:'dias'" item="item" class="item item-icon-right" ng-click="verTorneo(torneo.torneo_id)">
{{torneo.torneo_nombre}} {{torneo.dias}}
<i class="icon ion-ios-arrow-right"></i>
</ion-item>

app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;

var array = [];
for(var objectKey in input) {
array.push(input[objectKey]);
}

array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
return array;
}
})


This function directs me the numbers from lowest to highest, but have not been able to pull negative last. The order is as follows:

-3
-1
2
10


What I want is

2
10
-1
-3

Answer

Did you tried

array.sort(function(a, b){
    a = parseInt(a[attribute]);
    b = parseInt(b[attribute]);
    var A2 = (a < 0) ? 1 : 0;
    var B2 = (b < 0) ? 1 : 0;
    return (A2 == B2) ? a - b : A2 - B2;
});