0

I have to sort an array of objects based on a status value coming from the backend. The array has to be sorted in order of a priority array as:

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

I have my function like:

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

  }

My example enrolments object:

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

So far the sorted array is returning the same array as enrolments array and is not sorted. What ccould be wrong in my code? My enrolments array may or may not have all the statuses mentioned in my priority array. It may contain some of it or more than one enrolment with same 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"}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Mohit Harshan
  • 1,916
  • 1
  • 18
  • 41

1 Answers1

1

it requires a number as output not boolean so you can change it to use this

getActiveEnrolment(enrolments) {
    console.log(enrolments)
    const enrolmentsFiltered = enrolments.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(enrolmentsFiltered);

  }
Barkha
  • 702
  • 3
  • 8