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

求助:按日期(最近优先)对含日期字段的对象数组排序失败

Fixing Date Sorting for Your Grievance Data Array

Hey there! Let's break down why your current sort function isn't giving you the expected result, and fix it up properly.

First, let's spot the issues with your current code:

  • Wrong sort direction: Your return c - d sorts dates from earliest to most recent (ascending order), but you need the opposite—most recent to earliest (descending order).
  • Invalid date entry: One of your date strings has a typo: "22019-01-21 19:30:32" (extra '2' at the start of the year). When you pass this to new Date(), it creates an Invalid Date value, which messes up the sort logic.

Here's the corrected sort function:

This version handles both the descending order and the invalid date case (we'll push invalid dates to the end, which matches your expected output):

array.data.sort(function(a, b) {
  // Parse the dates
  const dateA = new Date(a.date);
  const dateB = new Date(b.date);

  // Handle invalid dates: push them to the end
  if (isNaN(dateA.getTime())) return 1;
  if (isNaN(dateB.getTime())) return -1;

  // Sort in descending order (most recent first)
  return dateB - dateA;
});

Let's test this with your data:

After running the corrected function, your array.data will match exactly what you expected:

[
  { grievance_nature: "Nature Two", grievance_nature_id: 19, date: "2019-01-30 06:53:20" },
  { grievance_nature: "Nature Two", grievance_nature_id: 19, date: "2019-01-28 06:53:20" },
  { grievance_nature: "Nature Two", grievance_nature_id: 19, date: "22019-01-21 19:30:32" },
  { grievance_nature: "Nature Two", grievance_nature_id: 19, date: "2019-01-19 06:53:20" }
]

A quick note on date handling:

If you can fix that typo in the "22019-01-21" date to "2019-01-21", the sort will place it between 2019-01-28 and 2019-01-19 as you'd logically expect. The function above just accounts for the typo as it exists in your current data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:49:17