简体   繁体   中英

Angularjs - Deep Orderby - How to handle multiple layers of sorting?

I have a table of Incidents ( See array below) and im trying to sort them by State in the order of Initial > Ongoing > InReview > Resolved. Then within the organised State, I want to sort them by Priority so P1>P2>P3 and then organise the priority by Start_date so that the oldest is on the top.

I cant seem to find any example of such granularity of sorting online. Would anyone know how I would go about this?

Here is my array:

$scope.Incidents=  [{
  Start_date: "2021-12-01 09:20:00"
  State: "Initial"
  Priority: "P1"
  },{
  Start_date: "2021-11-01 07:20:00"
  State: "Ongoing"
  Priority: "P2"
  },{  Start_date: "2021-10-01 05:20:00"
  State: "Resolved"
  Priority: "P3"
  },{  Start_date: "2021-12-01 09:48:00"
  State: "Ongoing"
  Priority: "coach"
  },{  Start_date: "2021-11-20 06:55:00"
  State: "InReview"
  Priority: "P1"
  },{  Start_date: "2021-08-01 09:20:00"
  State: "InReview"
  Priority: "P2"
  
}];


<div ng-repeat="incident in Incidents| orderBy:Custom_order >
     <div>{{incident.Priority}} - {{incident.Priority}} - {{incident.Start_date}}</div>
</div>

Here is an idea how to write a sort function that can easily be adapted to other sorting problems of this kind.

let sort_order = ["Initial", "Ongoing", "InReview", "Resolved"];
let sort_func = function(a, b){
  return sort_order.indexOf(a.State) - sort_idx.indexOf(b.State);
}

$scope.Incidents.sort(sort_func);

The sequence inside sort_order will define the order. In case you want the order reversed, just append .reverse() to .sort(...) .

Petr`s comment sent me into the right direction. Found a super easy solution that i havent seen anywhere here or online.

Heres what i added in my ng-repeat:

<div ng-repeat="incident in Incidents| orderBy:[Custom_order_State,Custom_order_Priority, 'Start_date'] >
     <div>{{incident.State}} - {{incident.Priority}} - {{incident.Start_date}}</div>
</div>

In my controller I created 2 custom order functions like so:

$scope.Custom_order_State= function (incident) {

    if(incident.State=== 'Initial'){
        return 1;
    }
    if(incident.État === 'Ongoing'){
        return 2;
    }
    if(incident.État === 'InReview'){
        return 4;
    }           
    if(incident.État === 'Resolved'){
        return 5;
    }   
        

};




$scope.Custom_order_Priority= function (incident) {

    if(incident.Priority=== 'P1'){
        return 1;
    }
    if(incident.Priority=== 'P2'){
        return 2;
    }
    if(incident.Priority=== 'P3'){
        return 3;
    }           

};

Its working perfectly on my end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM