You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现按指定时段顺序排序对象数组的自定义比较函数

自定义时间段顺序的数组排序方案

嘿,这个问题我之前也踩过坑!默认的字母序排序确实会把顺序搞成afternoon→evening→morning,完全不符合我们的需求。不过咱们可以通过自定义排序优先级映射来解决这个问题,思路很简单:

  • 先给每个day type设定一个固定的优先级数字,对应你想要的展示顺序
  • 在sort的对比函数里,用这个数字来替代原字符串进行比较

具体实现步骤

  1. 定义优先级映射对象
    我们把想要的顺序转换成数字,数字越小越靠前:

    // 定义目标顺序:morning > afternoon > evening
    const dayPriority = {
      morning: 0,
      afternoon: 1,
      evening: 2
    };
    
  2. 编写对比函数并排序
    把数组里每个对象的day type转换成对应的优先级数字,然后用数字相减来决定排序顺序:

    // 假设你的数组是这个样子
    const yourDayArray = [
      { "day type": "evening", otherProp: "..." },
      { "day type": "morning", otherProp: "..." },
      { "day type": "afternoon", otherProp: "..." }
    ];
    
    // 执行排序
    yourDayArray.sort((a, b) => {
      // 取出两个元素的优先级数字
      const priorityA = dayPriority[a["day type"]];
      const priorityB = dayPriority[b["day type"]];
      // 数字相减:负数则a在前,正数则b在前,0保持原顺序
      return priorityA - priorityB;
    });
    

额外处理:兼容未知的day type值

如果你的数组里可能出现不在morning/afternoon/evening范围内的day type,可以给它们设置一个更高的优先级,让它们自动排到最后:

yourDayArray.sort((a, b) => {
  // 用??运算符给未知类型默认分配优先级3(排在最后)
  const priorityA = dayPriority[a["day type"]] ?? 3;
  const priorityB = dayPriority[b["day type"]] ?? 3;
  return priorityA - priorityB;
});

这样处理后,不管原始数组的顺序有多乱,最终都会严格按照morning→afternoon→evening的顺序展示啦!

内容的提问来源于stack exchange,提问作者Rasmus Puls

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:38:38