JavaScript自定义排序

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

详细内容见文章:https://juejin.im/post/6844904029496016910

你可能感兴趣的:(JavaScript自定义排序)