Arranging the list based on priority

I have an array called criticalityTypes that contains three different levels of criticality: 'CRITICALITY_LOW', 'CRITICALITY_HIGH', and 'CRITICALITY_MEDIUM'.

Currently, the order of these criticality types is random, which means sometimes 'CRITICALITY_LOW' is in position 1, and other times it's at position 2 or 'CRITICALITY_MEDIUM' at position 0.

What I want to achieve is to sort these criticality types in a specific order regardless of how they are randomly arranged. The desired order is: ['CRITICALITY_HIGH', 'CRITICALITY_MEDIUM', 'CRITICALITY_LOW'].

I've attempted to use a sorting function like this:

return criticalityTypes.sort((a, b) => {
    if (a < b) return -1;
    if (a > b) return 1;
});

However, my current approach has not been successful. Can anyone provide assistance on how I can achieve the desired ordering?

Answer №1

If you have a list of objects and want to sort them based on a specific order, one way to do it is by sorting the objects according to the values difference.

var priorityLevels = ['LOW', 'HIGH', 'MEDIUM'],
    order = { HIGH: 1, MEDIUM: 2, LOW: 3 };

priorityLevels.sort((a, b) => order[a] - order[b]);

console.log(priorityLevels);

Answer №2

Here's an alternative approach:

const priorityLevels = ['LOW_PRIORITY', 'HIGH_PRIORITY', 'MEDIUM_PRIORITY'];
let sortedTasks = [];
let targetOrder = ['HIGH_PRIORITY', 'MEDIUM_PRIORITY', 'LOW_PRIORITY'];

 for (var j = 0; j < targetOrder.length; j++) {
    if (priorityLevels.indexOf(targetOrder[j]) > -1) {
        sortedTasks.push(targetOrder[j]);
    }
 }

 console.log(sortedTasks);

Answer №3

The issue at hand stems from the lack of clear definition for what constitutes an "order" in relation to the items provided by the API. These items are more conceptual in nature rather than being quantifiable, making it difficult to assign a numerical value as an order. The string representation serves primarily for display purposes.

While you may not have the ability to modify the API itself, if there are only three possible items and they always need to be displayed in a specific sequence, one approach could be to create a placeholder function that mimics the current sorting behavior. This placeholder can serve as a temporary solution until a more concrete method of determining the ordering numerically is available; after all, ascending or descending orders rely on quantifiable values to make sense.

function criticalityTypes(a,b){
    return ['CRITICALITY_HIGH', 'CRITICALITY_MEDIUM', 'CRITICALITY_LOW'];
}

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

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

When extracting a value from an HTML textarea that contains multiple lines of text inputted by the user, the JSON becomes invalid

Here is the JSON format I am working with: { questionID: int studentAnswer: "String" } The issue I am facing is that the studentAnswer field is currently only capable of holding input from a single line in an HTML textarea. If I input text that spa ...

What makes traversing through an array of Structs so much faster compared to an array of Classes?

I am in the process of developing a game using Swift and I have a static array of positional data that I am utilizing for processing within the game loop. Initially, I had been using an array of Structs to store this data but eventually made the decision t ...

The append() function works only the first time when the same code is being appended to the same div

$('.addvalue').change(function(){ val_id = this.id; count_new_btn++; count_new_inp++; if( $('#'+val_id).val() == '1'){ $('#div'+ val_id).append('<input ...

Trying to use 'cpa' before it is initialized will result in an error

I encountered the error stated above while using this particular route: router.put('/edit/:id', async (req, res) => { const cpa = await CPASchema.findById(req.params.id).then(() => { res.render('edit', { cpa:cpa }); cons ...

PHP - Updating elements in a multidimensional array

Here is the code snippet I am working with: $mainArray = Array( [0] => Array ( [0] => 06 ) [1] => Array ( [0] => 15 ) ) $array1 = array("1","2","3","4","5","6","7","8","9","10","11", ...

Execute a series of repetitive HTTP GET requests and remain patient for all of them to complete

I am working with a REST service that provides a list of 'Json' objects, where each object may contain a link to another resource of the same class. To fetch all these resources recursively starting from a specific one, I have written the followi ...

Parsing a JSON array into an Android spinner from an ASP.NET webservice that returns a string can be achieved by following these steps

[ { "value": "--NA--", "id": "251" }, { "value": "Adilabad", "id": "1346" }, { "value": "Yavatmal", "id": "1478" } ] Looking for a way to effectively parse the JSON data above into an Android spinner from a JSON web service. I hav ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Converting query results to JSON in Symfony3

Having an issue with returning my posts array as JSON in Symfony due to the fact that it returns array with entity objects. This is my code: public function indexAction() { $em = $this->getDoctrine()->getManager(); $posts = $em->getRepo ...

Curious about retrieving a value in a Bootstrap confirm modal?

Although it may seem like a silly question, I am struggling to figure out how to wait for the confirmation button to return a value in Javascript. Since Javascript is single-threaded, I need to implement a callback function that will wait until a button is ...

Is there a way to transform a Selenium script into standard Javascript code?

Is there a way to convert a Selenium script into pure Javascript code? ...

Ensuring form field accuracy through server-side validation using Ajax - Mastering the art of Ajax

I am in need of implementing Ajax to validate my form fields, currently I have a javascript validation set up. Is it possible to reuse my existing javascript code and integrate Ajax for form validation? HTML Form <form method="post" action="ajax/valid ...

Using multiple parameters in a GET request

url: "../api/api.php? fxn:" + encodeURIComponent(getCatergories) & "jsn"= +encodeURIComponent{"code":"1"}, var app = angular.module('MyTutorialApp',[]); app.controller("MainController", function($scope,$http){ $scope.loadpeople= functio ...

Acquiring a function from an express server and seamlessly executing it on a web page using a script tag

Is it possible to return a function from an express server and execute it in a browser? I have deployed a function on Google Cloud Platform (Cloud Functions) and aim to execute it in a web application using a script tag. The function is written in Nodejs ...

The command "npm run build" is failing and encountering errors within the webpack project

Today, when I ran npm run build in the terminal, my project stopped running and displayed 90 errors and 13 warnings. It was working fine yesterday, so I'm not sure what the issue could be. The only change I made was to a line of JavaScript code that i ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

Adjusting Grid Posts to a Consistent Size (Featuring Photo Posts with Captions Below)

I'm attempting to adjust the size of posts in grid mode on Tumblr. I've discovered that I can modify the width of each post using CSS. However, I'm struggling to locate where I can set the height of a grid post to a specific size. For inst ...