【问题标题】:Javascript - How to find the closest number (with working example)Javascript - 如何找到最接近的数字(有工作示例)
【发布时间】:2022-12-21 23:45:28
【问题描述】:

我正在尝试编写一个代码,根据会话数组计算下一个会话是什么。所有已经超过结束日期的日期都应该被忽略.我想我接近一个解决方案,但我不知道如何完成这个......

const sessions = [{
    "end": "2022-12-28T06:15:00Z",
    "start": "2022-12-23T06:00:00Z" // This should be the next session because 2022-12-23T06:00:00Z is closer to now than 2022-12-31T06:00:00Z (last entry)
  },
  {
    "end": "2022-12-20T06:00:00Z", // This date already passed (Today is 21st December)
    "start": "2022-12-18T06:00:00Z"
  },
  {
    "end": "2023-01-26T06:00:00Z",
    "start": "2022-12-31T06:00:00Z"
  }
];

const nextSession = {};

sessions.forEach(session => {
  const sessionStart = new Date(session.start).getTime();
  const sessionEnd = new Date(session.end).getTime();
  const now = new Date().getTime();
  // Calculate the difference between now and the session start
  const diffStartTime = sessionStart - now;
  console.log('Diff Start: ' + diffStartTime);
  // Calculate the difference between now and the session end
  const diffEndTime = sessionEnd - now;
  console.log('Diff End: ' + diffEndTime);

  // TODO how to get the next session?
});

有什么帮助吗?

【问题讨论】:

  • 您可以通过遍历所有会话并跟踪最近的会话(因此开始差异是最低的正值,因此忽略负值)并在最后返回它来在 O(n) 复杂度中执行此操作。
  • @rowan-vr 会话不会那么大。我认为最多 100 个条目
  • 你缺少的主要是一些簿记来跟踪最近的(将来),你可以通过将它与 nextSession 进行比较并将它存储在 nextSession 中(如果它比当前的 nextSession 更近)来做到这一点

标签: javascript


【解决方案1】:

我会用两步法来做到这一点。先过滤掉所有过期的session,然后排序最新的session(按照start)在第一个元素

const sessions = [{
    "end": "2022-12-28T06:15:00Z",
    "start": "2022-12-23T06:00:00Z" // This should be the next session because 2022-12-23T06:00:00Z is closer to now than 2022-12-31T06:00:00Z (last entry)
  },
  {
    "end": "2022-12-20T06:00:00Z", // This date already passed (Today is 21st December)
    "start": "2022-12-18T06:00:00Z"
  },
  {
    "end": "2023-01-26T06:00:00Z",
    "start": "2022-12-31T06:00:00Z"
  }
  ];

const filteredSessions = sessions
               .filter(item => new Date(item.end) > new Date())
               .sort((a,b) => new Date(a.start) - new Date(b.start))

if (filteredSessions.length) console.log(filteredSessions[0])

【讨论】:

    猜你喜欢
    • 2012-06-02
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2010-09-24
    • 2021-07-27
    相关资源
    最近更新 更多