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

JavaScript中基于首行日期对二维数组行排序的解决方法

基于首行日期时间对二维数组列排序的解决方案

问题分析

给定二维数组,首行为时间字符串,需要按时间降序排列所有行的对应列(从最晚到最早),其他行元素跟随首行列的顺序同步调整。

实现步骤

  1. 提取首行的时间数据,为每个时间绑定其原始列索引,确保排序后能准确映射到其他行的对应元素。
  2. 将时间字符串转换为可比较的Date对象(补全固定日期避免解析异常),用于排序逻辑。
  3. 对绑定了索引的时间数组按时间降序排序。
  4. 遍历原数组的每一行,根据排序后的索引顺序重新排列元素,生成最终结果数组。

代码实现

const data = [
  ['4:23:28 PM', '4:24:01 PM', '4:24:39 PM', '4:26:05 PM'],
  [1, 2, 3, 0],
  [4, 5, 3, 2]
];

// 生成带原始索引的时间数组
const timeWithIndices = data[0].map((time, index) => ({
  time,
  index
}));

// 按时间降序排序:补全日期确保Date解析正确
timeWithIndices.sort((a, b) => {
  const dateA = new Date(`2024-01-01 ${a.time}`);
  const dateB = new Date(`2024-01-01 ${b.time}`);
  return dateB - dateA;
});

// 提取排序后的索引顺序
const sortedIndices = timeWithIndices.map(item => item.index);

// 对每一行按索引顺序重排
const sortedData = data.map(row => sortedIndices.map(index => row[index]));

console.log(sortedData);
// 输出结果与预期一致:
// [
//   ['4:26:05 PM', '4:24:39 PM', '4:24:01 PM', '4:23:28 PM'],
//   [0, 3, 2, 1],
//   [2, 3, 5, 4]
// ]

关键说明

  • 补全固定日期(如2024-01-01)是为了避免Date对象因缺少日期信息导致的解析错误,确保时间比较的准确性。
  • 绑定原始索引是核心逻辑:排序的是列的顺序,必须通过索引映射保证其他行的元素跟随对应列同步移动。

内容的提问来源于stack exchange,提问作者code now

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:32:44