从日期数组中查找缺少的日子javascript [英] Find missing day from array of dates javascript

查看:45
本文介绍了从日期数组中查找缺少的日子javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从API获取一系列日期:

I am getting an array of day dates from an API:

0:{date: "2016-11-17T00:00:00",…}
1:{date: "2016-11-18T00:00:00",…}
2:{date: "2016-11-19T00:00:00",…}
3:{date: "2016-11-21T00:00:00",…}
4:{date: "2016-11-22T00:00:00",…}
5:{date: "2016-11-23T00:00:00",…}

在此示例中,该数组缺少该日期:

In this example the array is missing this date:

{date: "2016-11-20T00:00:00",…}

从Java或Angular中的日期数组中查找缺少的日子的最佳方法是什么?

What is the best way to find a missing day from an array of dates in Javascript or Angular?

这样我以后就可以将其作为禁用日传递给日期选择器.

So that I later would be able to pass it to a datepicker as a disabled day.

推荐答案

检查一下:

  1. 首先,您可以使用 Array.prototype.sort

然后使用 Array.prototype.reduce 哈希表查找丢失的日期

Then use Array.prototype.reduce and a hash table to find the missing dates

下面的代码段中提供了演示:

Demo given in snippet below:

var array=[
  {date:"2016-11-17T00:00:00"},
  {date:"2016-11-19T00:00:00"},
  {date:"2016-11-18T00:00:00"},
  {date:"2016-11-21T00:00:00"},
  {date:"2016-11-22T00:00:00"},
  {date:"2016-11-23T00:00:00"},
  {date:"2016-11-27T00:00:00"}
];

var result = array.sort(function(a,b){
   return Date.parse(a.date) - Date.parse(b.date);
}).reduce(function(hash){
  return function(p,c){
    var missingDaysNo = (Date.parse(c.date) - hash.prev) / (1000 * 3600 * 24);
    if(hash.prev && missingDaysNo > 1) {
      for(var i=1;i<missingDaysNo;i++)
        p.push(new Date(hash.prev+i*(1000 * 3600 * 24)));
    }
    hash.prev = Date.parse(c.date);
    return p;
  };
}(Object.create(null)),[]);

console.log(result);

.as-console-wrapper{top:0;max-height:100%!important;}

这篇关于从日期数组中查找缺少的日子javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆