如何在给定的开始日期和结束日期之间的数组中添加丢失的数据条目

时间:2019-04-08 11:10:30

标签: javascript jquery

我有一个名为plot_data的数组。因为我有两个对象属性,日期x和值y。日期实际上是过去的日期。在该数组中,多个地方的某些地方缺少一些日期。因此,无论错过什么日期,我都希望将其添加到数组中。

plot_data数组就是这样

0: {x: Fri Apr 06 2018 22:30:00 GMT-0500 (Central Daylight Time), y: 93.9}
1: {x: Sat Apr 07 2018 09:00:00 GMT-0500 (Central Daylight Time), y: 69.3}
2: {x: Tue Apr 10 2018 10:00:00 GMT-0500 (Central Daylight Time), y: 71.2}
3: {x: Wed Apr 11 2018 11:00:00 GMT-0500 (Central Daylight Time), y: 67.2}
4: {x: Sat Apr 14 2018 10:00:00 GMT-0500 (Central Daylight Time), y: 71.2}
5: {x: Sun Apr 15 2018 11:00:00 GMT-0500 (Central Daylight Time), y: 67.2}

我想要这样的数组输出。

0: {x: Fri Apr 06 2018 22:30:00 GMT-0500 (Central Daylight Time), y: 93.9}
1: {x: Sat Apr 07 2018 09:00:00 GMT-0500 (Central Daylight Time), y: 69.3}
2: {x: Sun Apr 08 2018 09:00:00 GMT-0500 (Central Daylight Time), y: null}
3: {x: Mon Apr 09 2018 09:00:00 GMT-0500 (Central Daylight Time), y: null}
4: {x: Tue Jun 10 2018 10:00:00 GMT-0500 (Central Daylight Time), y: 71.2}
5: {x: Wed Jun 11 2018 11:00:00 GMT-0500 (Central Daylight Time), y: 67.2}
6: {x: Thu Jun 12 2018 10:00:00 GMT-0500 (Central Daylight Time), y: null}
7: {x: Fri Jun 13 2018 11:00:00 GMT-0500 (Central Daylight Time), y: null}
8: {x: Sat Jun 14 2018 10:00:00 GMT-0500 (Central Daylight Time), y: 71.2}
9: {x: Sun Jun 15 2018 11:00:00 GMT-0500 (Central Daylight Time), y: 67.2}

我不知道该怎么做,因为我们必须考虑一个月中的约会次数。请帮忙。

1 个答案:

答案 0 :(得分:1)

您可以通过添加24小时来获取下一个日期,那么您就不必关心该月中的日期了。

我已删除了时区,您可以根据需要进行设置。

let arr = [{x: 'Fri Apr 06 2018 22:30:00', y: 93.9},
{x: 'Sat Apr 07 2018 09:00:00', y: 69.3},
{x: 'Tue Apr 10 2018 10:00:00', y: 71.2},
{x: 'Wed Apr 11 2018 11:00:00', y: 67.2},
{x: 'Sat Apr 14 2018 10:00:00', y: 71.2},
{x: 'Sun Apr 15 2018 11:00:00', y: 67.2}]

let i=0;
while(i < arr.length-1) {
	let nextday = new Date(new Date(arr[i].x).getTime() + 24 * 60 * 60 * 1000);
	if(nextday.getDay() != (new Date(arr[i+1].x)).getDay()) {
		arr.splice(i+1, 0,  {x: nextday.toString(), y: null});
	};
        i++
}

console.log(arr)