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

如何按特定规则高效排序含可选日期字段的对象数组?

解决方案

不需要拆分数组分类排序,直接通过Array.sort()的比较函数就能一次性实现需求。核心思路是给缺失的month和day字段设置默认值,结合时间精度优先级完成排序:

  1. 给仅含year的对象默认month=1、day=1;给含year+month的对象默认day=1
  2. 优先按year→month→day的数值从小到大排序,保证时间先后顺序
  3. 若时间节点完全重合,精度越低的对象(仅year > year+month > 完整日期)排越靠前

完整代码

const array = [ 
  {year:'1938', month:'6', day:'3'},
  {year:'1935', month:'5', day:'3'}, 
  {year:'1935', month:'', day:''}, 
  {year:'1935', month:'5', day:''}, 
  {year:'1934', month:'3', day:''}, 
  {year:'1934', month:'3', day:'15'}, 
  {year:'1934', month:'', day:''}
];

// 排序比较函数
const compareTimeItems = (a, b) => {
  // 获取精度等级:0=仅year,1=year+month,2=完整日期
  const getPrecision = obj => {
    if (obj.month === '' && obj.day === '') return 0;
    if (obj.month !== '' && obj.day === '') return 1;
    return 2;
  };
  const precisionA = getPrecision(a);
  const precisionB = getPrecision(b);

  // 转换为数值类型,缺失字段设默认值
  const yearA = Number(a.year);
  const monthA = a.month === '' ? 1 : Number(a.month);
  const dayA = a.day === '' ? 1 : Number(a.day);
  
  const yearB = Number(b.year);
  const monthB = b.month === '' ? 1 : Number(b.month);
  const dayB = b.day === '' ? 1 : Number(b.day);

  // 先按年份排序
  if (yearA !== yearB) {
    return yearA - yearB;
  }
  // 年份相同按月份排序
  if (monthA !== monthB) {
    return monthA - monthB;
  }
  // 月份相同按日期排序
  if (dayA !== dayB) {
    return dayA - dayB;
  }
  // 时间完全相同时,精度低的排前面
  return precisionA - precisionB;
};

// 执行排序
const sortedArray = array.sort(compareTimeItems);
console.log(sortedArray);

排序结果

[
  { year: '1934', month: '', day: '' },
  { year: '1934', month: '3', day: '' },
  { year: '1934', month: '3', day: '15' },
  { year: '1935', month: '', day: '' },
  { year: '1935', month: '5', day: '' },
  { year: '1935', month: '5', day: '3' },
  { year: '1938', month: '6', day: '3' }
]

该结果完全符合需求:既按时间先后排序,又保证同时间区间内精度低的对象优先排列。

内容的提问来源于stack exchange,提问作者Calin Onaca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:15:35