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
];
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;
}
You can have a loop which counts from first timestamp to the last, incremented by 60 seconds. Then populate a new array with current values + missing values like below.
var dataParsed = [];
for(var i=data[0][0], j=0; i<=data[data.length-1][0]; i+=60000) {
if(i == data[j][0]) {
dataParsed.push(data[j]);
j++;
} else {
dataParsed.push([i, 0]);
}
}
©2020 All rights reserved.