在时间戳日期范围内生成空数据| Java脚本 [英] Generate empty data between the range of a timestamp date | Javascript

查看:123
本文介绍了在时间戳日期范围内生成空数据| Java脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一些带有时间戳的统计数据.我想将其绘制在图表上. 数据以固定步长(1sec)递增,但是其中一些丢失. 我想用自己生成的时间戳填补这一空白.

I get some statistic data with timestamps. I want to plot it on the chart. Data are increment with fixed step (1sec) but some of them are missing. I want to fill this gaps with self generated timestamp.

// exmaple data form 18:00 to 18:47 (step 60000ms)

var data = [
    [1425056400000, 1123], //18:00
    [1425056460000, 1124], //18:01
    [1425056520000, 1125], //18:02
    [1425056580000, 1126], //18:03
    [1425056640000, 1140], //18:04
    [1425057840000, 2123], //18:24
    [1425057900000, 2133], //18:25
    [1425057960000, 2141], //18:26
    [1425059160000, 5129], //18:46
    [1425059220000, 5129]  //18:47
];


// required result
var dataParsed = [
    [1425056400000, 1123], //18:00
    [1425056460000, 1124], //18:01
    [1425056520000, 1125], //18:02
    [1425056580000, 1126], //18:03
    [1425056640000, 1140], //18:04
    [1425056700000, 0], //18:05
    [1425056760000, 0], //18:06
    [1425056820000, 0], //18:07
    //(...)
    [1425057780000, 0], //18:23
    [1425057840000, 2123], //18:24
    [1425057900000, 2133], //18:25
    [1425057960000, 2141], //18:26
    //(...)
    [1425058800000, 0], //18:40
    //(...)
    [1425059160000, 5129], //18:46
    [1425059220000, 5129]  //18:47
];

如何使用JavaScript做到这一点?

How can I do this with JavaScript?

推荐答案

在遍历原始数组时,请检查当前元素是否为序列中的下一个元素.如果没有,请使用另一个循环来生成缺少的元素:

As you loop through the original array, check whether the current element is the next one in the sequence. If not, use another loop to generate the missing elements:

var dataParsed = [];
var lastTime = data[0][0];
var timeStep = 60000;
for (var i = 0; i < data.length; i++) {
    var curTime = data[i][0];
    if (curTime > lastTime + timeStep) {
        for (var time = lastTime + timeStep; time < curTime; time += timeStep) {
            dataParse.push([time, 0]);
        }
    }
    dataParse.push(data[i]);
    lastTime = curTime;
}

这篇关于在时间戳日期范围内生成空数据| Java脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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