Angularjs - Navigating the Depths of OrderBy: Effective Strategies for Handling Complex Sorting Structures

I have a collection of Incidents (displayed as an array below) that I need to sort meticulously by State, Priority, and Start_date. Specifically, I want them ordered in the sequence of Initial > Ongoing > InReview > Resolved for State, then Priority should be P1 > P2 > P3, and finally within each priority level sorted by Start_date from oldest to newest.

Despite searching online, I haven't been able to find any examples of such a detailed sorting requirement. Does anyone have suggestions on how I can achieve this?

Below is the representation of my incidents in an 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>

Answer №1

Check out this method for creating a flexible sort function that can be adjusted to handle different sorting scenarios.

const order_of_sort = ["Initial", "Ongoing", "InReview", "Resolved"];
const custom_sort_function = function(item1, item2){
  return order_of_sort.indexOf(item1.State) - order_of_sort.indexOf(item2.State);
}

$scope.Incidents.sort(custom_sort_function);

The order of the elements in order_of_sort will determine the sorting sequence. If you need the sorting order to be reversed, simply add .reverse() after calling .sort(...).

Answer №2

Thanks to Petr's insight, I was able to discover a surprisingly simple solution that seems to be unique to my situation.

Here is the snippet I added within 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 defined 2 custom order functions like this:

$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;
    }           

};

This setup is functioning flawlessly for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

swap out a JavaScript function for a fresh function

In our ordering system, there is a hidden function that I cannot access. Interestingly, this function contains a spelling error which causes a grammar issue to appear in a popup when a user interacts with it. Is there any way for me to either modify the t ...

Invoking an express route using JavaScript

After successfully defining some routes, including a text input search field at the top of the page, I created a listener function as shown below: $('#tags').keypress(function(e) { if (e.keyCode == 13 && document.getElementById('t ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

Transmit JSON information from one webpage and dynamically retrieve it from another page via AJAX while both pages are active

I am attempting to transfer JSON data from page1 when the submit button is clicked and then retrieve this data dynamically from page2 using AJAX in order to display it in the console. I am unsure of the correct syntax to accomplish this task. There was a s ...

How can state be shared between sibling components in React?

As someone who is relatively new to React, I am seeking guidance on the proper method of passing states between components. While I did come across a similar inquiry on Stack Overflow, I would appreciate if someone could provide a specific solution for my ...

Comparing the length of an array to whether the length of the array is greater than

What distinguishes checking an array's length as a truthy value from verifying that it is greater than zero? In simple terms, is there any advantage in utilizing one of these conditions over the other: var arr = [1,2,3]; if (arr.length) { } if (arr ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

What significance does it hold when an unhandled rejection event lacks a reason field?

Our app tracks client-side errors using Rollbar, but we keep encountering a not very helpful error message from Safari and Chrome: [unhandledrejection] error getting `reason` from event Upon investigation, I found that this message is generated by Rollbar ...

Unable to retrieve information from service using Angular 1.6 and TypeScript

I'm having an issue retrieving data from a Service in my Controller. Here is the code for my Service file: import {IHttpService} from 'Angular'; export class MyService { public static $inject = ['$http']; constructor(private $htt ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Checking for the existence of inner directives after they have been rendered in AngularJS

While working on a view, I am using myDirective in the following manner: <div my-directive></div> The myDirective includes a template: <div> <div my-inner-directive></div> </div> My query is: How can I determine ...

Choose not to alter the display value during keyup and keydown events, while still triggering the change event

$(function(){ $(".cls_user_details select").keyup(function(){ $(".cls_user_details select").val("Profile"); }) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cls_user_setti ...

Using AngularJS to show content based on a callback function

I'm a beginner in angular and it seems like I might be overlooking something. For the registration form, I need users to provide their location. Depending on whether they allow/support navigator.geolocation, I want to display a drop-down menu for cho ...

Tips for utilizing the npm jQuery module effectively

What is the best way to import jquery into multiple modules in node? Should I make it a global variable, or should I use require('jquery') in each module that needs it? I encountered an error while attempting to utilize the package. TypeError: ...

How can I use vanilla JavaScript to retrieve all elements within the body tag while excluding a specific div and its descendants?

My goal is to identify all elements within the body tag, except for one specific element with a class of "hidden" and its children. Here is the variable that stores all elements in the body: allTagsInBody = document.body.getElementsByTagName('*&apos ...