从对象数组中查找最接近今天的日期

时间:2018-08-12 10:14:13

标签: javascript

我已经解析了一个像这样分割的CSV:

data[0]
>>Date:08/23/2018, Organizer:RadioShack, Event:Promotion

我在Find closest date in array with JavaScript中发现了一个有用的问题,但是我很难将其从日期数组调整为存储在对象数组中的日期。我的日期是从data[0]data[10]。它不是一个非常长的数据集,但是我想比我目前的粗略方法更好地编码它:

var dateArray = [];
dateArray[0] = data[0].Date;
dateArray[1] = data[1].Date;
…

console.log(dateArray.filter(function(d) {return d - today > 0; }))

这为我提供了今天日期之后的所有日期,这是一个开始,但是我仍然无法找到最接近今天的日期。

问题::我想也许我可以编写一个for循环来更快地给我该数组,但是我仍然想知道:有没有一种方法可以从数组中找到与今天的日期最接近的日期对象并将该日期存储在:

var closestEventDate = ???

2 个答案:

答案 0 :(得分:3)

您可以将dateArray减小为最接近今天的日期:

 const today = new Date();
 const closest = data.reduce((a, b) => a.Date - today < b.Date - today ? a : b);

实时示例:

var now = Date.now();
var ONE_DAY_IN_MS = 86400000;
function randomDate() {
  return new Date(now + (5 * ONE_DAY_IN_MS - Math.round(Math.random() * 10 * ONE_DAY_IN_MS)));
}
var data = [
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()}
];

console.log("Entries:");
data.forEach(function(entry) {
  console.log(entry.Date.toISOString());
});

const today = new Date();
const closest = data.reduce((a, b) => a.Date - today < b.Date - today ? a : b);

console.log("today", today.toISOString());
console.log("closest", closest.Date.toISOString());
.as-console-wrapper {
  max-height: 100% !important;
}

或今天之后最接近的

const today = new Date();
const closest = data.reduce((a, b) => {
  const adiff = a.Date - today;
  return adiff > 0 && adiff < b.Date - today ? a : b;
});

实时示例:

var now = Date.now();
var ONE_DAY_IN_MS = 86400000;
function randomDate() {
  return new Date(now + (5 * ONE_DAY_IN_MS - Math.round(Math.random() * 10 * ONE_DAY_IN_MS)));
}
var data = [
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()},
  {Date: randomDate()}
];

console.log("Entries:");
data.forEach(function(entry) {
  console.log(entry.Date.toISOString());
});

const today = new Date();
const closest = data.reduce((a, b) => {
  const adiff = a.Date - today;
  return adiff > 0 && adiff < b.Date - today ? a : b;
});

console.log("today", today.toISOString());
console.log("closest", closest.Date.toISOString());
.as-console-wrapper {
  max-height: 100% !important;
}

答案 1 :(得分:0)

除了乔纳斯的回答。使用 dayjs

的类似方法
arrayOfDates.reduce((a, b) => dayjs(a.Date).isAfter(dayjs(b.Date)) ? a : b);