Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sắp xếp mảng đối tượng theo thứ tự tham chiếu từ mảng khác trong JavaScript

Cho mảng đơn hàng có status và mảng statuses định nghĩa thứ tự ưu tiên. Sắp xếp đơn hàng theo thứ tự statuses.

Ví dụ

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

Kết quả

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