Arrange the objects in an array using a priority array as a guideline

I need assistance with sorting an array of objects based on a status value from the backend system. The sorting priority should follow a specific order defined in the priority array:

const priority = [
  "APPROVED",
  "WITHDRAW_PENDING",
  "PENDING",
  "WITHDRAWN",
  "CANCELLED",
  "REJECTED",
]

Currently, my sorting function looks like this:

getActiveEnrolment(enrolments) {
    console.log(enrolments)
    const enrolmentsFiltered = enrolments.sort((a, b) => priority.indexOf(a.status) > priority.indexOf(b.status));
    console.log(enrolmentsFiltered);

}

An example of the enrolments object being used:

{enrollable: {id: "fb9de5ae-2b13-49ce-ac58-e82db55c078b", itemdata: {…}, itemtype: "Course"}
id: "e66a34cd-1889-48ba-9a86-42eb87dfe86e"
status: "APPROVED"
user: "4fd79b04-9ed0-4942-84fc-9670f8a89050"}

Despite implementing the sort function, the array is not getting sorted as expected. It seems to be returning the same array as the original enrolments array. I'm unsure what could be causing this issue. Please note that the enrolments array may not necessarily include all the statuses listed in the priority array and can have duplicate statuses.

console.log:

   (3) [{…}, {…}, {…}]
    0: {id: "e66a34cd-1889-48ba-9a86-42eb87dfe86e", user: "4fd79b04-9ed0-4942-84fc-9670f8a89050", enrollable: {…}, status: "APPROVED"}
    1: {id: "a445d96a-3bac-42db-b4a8-682076dfc5a7", user: "4fd79b04-9ed0-4942-84fc-9670f8a89050", enrollable: {…}, status: "REJECTED"}
    2: {id: "16c5f940-3640-4d75-92d5-46a1f2257a02", user: "4fd79b04-9ed0-4942-84fc-9670f8a89050", enrollable: {…}, status: "PENDING"}
    length: 3
    __proto__: Array(0)


 (3) [{…}, {…}, {…}]
    0: {id: "e66a34cd-1889-48ba-9a86-42eb87dfe86e", user: "4fd79b04-9ed0-4942-84fc-9670f8a89050", enrollable: {…}, status: "APPROVED"}
    1: {id: "a445d96a-3bac-42db-b4a8-682076dfc5a7", user: "4fd79b04-9ed0-4942-84fc-9670f8a89050", enrollable: {…}, status: "REJECTED"}
    2: {id: "16c5f940-3640-4d75-92d5-46a1f2257a02", user: "4fd79b04-9ed0-4942-84fc-9670f8a89050", enrollable: {…}, status: "PENDING"}

Answer №1

Only accepting a number as an output, not boolean. You have the option to adjust it by utilizing this approach.

getActiveEnrollment(enrollments) {
    console.log(enrollments)
    const filteredEnrollments = enrollments.sort((a, b) => { 
    if (priority.indexOf(a.status) > priority.indexOf(b.status)) return 1;
    if (priority.indexOf(a.status) < priority.indexOf(b.status)) return -1;
    return 0;

    });
    console.log(filteredEnrollments);

}

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

Navigating programmatically to another page in Next.js can be easily achieved by utilizing the useRouter hook

Following a post request to an external API, my goal is to navigate back to the homepage. While I am familiar with React, this is my first experience using Next.js. Here's the snippet of code: export default function New({genres}) { const createMovie ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

Using Angular JS services and controllers in separate files may result in errors

Within my angularjs project, I manage the following files: /index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-wid ...

Exploring the utilization of properties within the composition API

Can props be shared between components using the composition API, or is it still necessary to use mixins for that purpose? For instance, if I have a "visible" prop that I want to reuse in 5 components, how can I define it once and reuse it efficiently wit ...

Tips for integrating map coordinates into a URL

In my React app, there is a Leaflet map that I want to update the URL dynamically with position information (latitude, longitude, and zoom) whenever the map is moved. For example: app.com/lat,lng,z/myroutes Furthermore, default values for lat, lng, z sho ...

Issue with modifying DataTable's body content via Ajax request

I am working with a DataTable and trying to load data through an ajax call. However, the first line always displays: "No data available in table" https://i.sstatic.net/7gFKx.png Despite this message, the ajax-loaded data is displayed below it. How can I ...

Styling checkboxes and adding onClick functionality in JavaScript

I want to customize the appearance of my checkboxes while still maintaining an onClick function. I came across a code for styling that hides the actual checkbox and stylizes the label, but it seems to disable the JavaScript onClick function. Is there a way ...

How can I retrieve the element that the user is currently typing in within a designMode iframe?

I have a situation where I have an iframe that allows users to type and edit various divs within it. However, there is one specific div that should not be editable by the user. I have tried to prevent users from clicking on the div using JavaScript: docum ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Having trouble with JavaScript's variable scoping?

Currently, I am using Node.js and mongoose, but I have encountered a challenging issue: var dbvar; doc_model .findOne({aadhar}) .then(()=>{ dbvar=1; }); paramedic_model .findOne({aadhar}) .then(()=>{ dbvar=2; }); console.log(dbva ...

Utilizing jQuery to dynamically calculate real-time output from user input in a form

My task involves creating a form where the user fills out certain values, and I want to display a calculated value based on those inputs at the bottom of the form. Unfortunately, I'm not seeing any output at all. Here is the HTML form I have attempte ...

Unable to retrieve HTTP call response during debugging, although it is visible in the browser

When I send an HTTP request to create a record, I am able to see the added record id in the Network section of browsers like Chrome and Firefox. However, when I try to debug the code and retrieve the same id value, I encounter difficulties. I have tried us ...

The Material UI date range picker fails to close once a selection has been made

I'm currently using the Material UI date range picker, but I've encountered an issue. After selecting the dates, the date picker does not close automatically. How can I make it close once the dates are selected? I couldn't find any specific ...

What could be causing my dropdown links to malfunction on the desktop version?

I've been developing a responsive website and encountering an issue. In desktop view, the icon on the far right (known as "dropdown-btn") is supposed to activate a dropdown menu with contact links. However, for some unknown reason, the links are not f ...

Tips for creating a vertical Angular Material slider with CSS

Attempting to modify the angular material directive to render vertically has been a challenge. I experimented with using transform:rotate in the CSS, however, it resulted in the slider behaving and rendering differently. md-slider { position: absolute ...

The magnitude of each new keystroke is squared compared to its predecessor

exploring the relationship between keyboard and console inputs Each subsequent e.key entry is occurring twice as frequently as the previous one. Once it reaches 8-9 characters, the rendering frequency skyrockets to over 1000 times per character. Here&apos ...

Angular 8 is encountering an issue with an undefined global variable, specifically the variable "this

I have a model named Chat, defined as follows: export class Chat { chatId?: number; chatUser1?: string; chatUser2?: string; chatStatus?: string; created_at?: any; updated_at?: any; deleted_at?: any; } In the component, I need to retrieve the value of ch ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

Tips for fixing footer accordion overlap issues

Just starting out with jQuery and using the Accordion feature. Noticed that when I click on the accordion, it overlaps with the footer. How can I prevent this from happening? Here is the code for the footer - <footer> <div class="row footer_ ...

Are there any equivalents to template literals in the opposite direction?

Template literals make it super simple to create output like this: const age = 22; console.log(`Paul is ${age} years old.`) // => Paul is 22 years old. As I work on extracting information from text, I wonder if there's a way to do the reverse usi ...