开门见山,直接上函数
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]]
);
};
此函数的参数是一个对象,里面有三个属性,data是待排序的数组,sortBy是存放排序规则的数组,sortField则是根据哪一个字段进行排序。
比方说我们有以下数组:
const tasks = [
{ id: 1, title: "Job A", status: "done" },
{ id: 2, title: "Job B", status: "inProgress" },
{ id: 3, title: "Job C", status: "todo" },
{ id: 4, title: "Job E", status: "inProgress" },
{ id: 5, title: "Job F", status: "todo" }
];
现在想对它进行排序,并且是依据status字段的自定义排序,假设我们想把status值为"inProgress"的排在最前,其次是值为"todo",最后是值为"done"的:
const sortBy = ["inProgress", "todo", "done"];
调用自定义排序函数,对status属性进行排序:
customSort({ data: tasks, sortBy, sortField: "status" });
本文转载自:
作者:HEY_439
链接:https://www.jianshu.com/p/c9b909afc7e8