根据优先级数组对数组对象进行排序

时间:2019-09-27 10:13:56

标签: javascript typescript

我必须根据来自后端的状态值对对象数组进行排序。该数组必须按照优先级数组的顺序排序:

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

我的功能如下:

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

  }

我的示例注册对象:

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

到目前为止,已排序的数组返回的数组与注册数组相同,并且未排序。我的代码有什么错?我的注册数组可能具有或不具有优先级数组中提到的所有状态。它可能包含其中的一部分或状态相同的一个或多个注册。

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"}

1 个答案:

答案 0 :(得分:0)

它需要一个数字作为输出而不是布尔值,因此您可以更改它以使用此

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);

  }