美文网首页
JavaScript自定义排序

JavaScript自定义排序

作者: 香草吧吧噗 | 来源:发表于2020-11-10 14:59 被阅读0次
    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自定义排序

          本文链接:https://www.haomeiwen.com/subject/aurjbktx.html