通过数组JavaScript对对象数组进行排序
假设我们有一个对象数组和一个字符串数组,如下所示:
示例
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' } ]