const tasks = [
{ id: 1, title: "Job A", status: "done" },
{ id: 2, title: "Job B", status: "inProgress" },
{ id: 3, title: "Job C", status: "todo" },
{ id: 3, title: "Job D", status: "onHold" },
{ id: 4, title: "Job E", status: "inProgress" },
{ id: 5, title: "Job F", status: "todo" }
];
const sortBy = ["inProgress", "todo", "done"];
const customSort = ({ data, sortBy, sortField }) => {
const sortByObject = sortBy.reduce(
(obj, item, index) => ({
...obj,
[item]: index
}),
{}
);
return data.sort(
(a, b) => sortByObject[a[sortField]] - sortByObject[b[sortField]]
);
};
const tasksWithDefault = tasks.map(item => ({
...item,
sortStatus: sortBy.includes(item.status) ? item.status : "other"
}));
console.log(
customSort({
data: tasksWithDefault,
sortBy: [...sortBy, "other"],
sortField: "sortStatus"
})
);
网友评论