通过 JavaScript 数组对对象数组进行排序

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/3 1:16:17

假设我们有一个对象数组和一个字符串数组,如下所示 −

示例

const orders = [
   { status: "pending"},
   { status: "received" },
   { status: "sent" },
   { status: "pending" }
];
const statuses = ["pending", "sent", "received"];

我们需要编写一个 JavaScript 函数,该函数接受两个这样的数组。该函数的目的应该是根据 statuses 数组的元素对 orders 数组进行排序。

因此,第一个数组中的对象应该根据第二个数组中的字符串进行排列。

示例

const orders = [
   { status: "pending" },
   { status: "received" },
   { status: "sent" },
   { status: "pending" }
];
const statuses = ["pending", "sent", "received"];
const sortByRef = (orders, statuses) => {
   const sorter = (a, b) => {
      return statuses.indexOf(a.status) - statuses.indexOf(b.status);
   };
   orders.sort(sorter);
};
sortByRef(orders, statuses); console.log(orders);

输出

控制台中的输出将是 −

[
   { status: 'pending' },
   { status: 'pending' },
   { status: 'sent' },
   { status: 'received' }
]

相关文章


有用资源