I am reading a cvs-file and one column contains unix timestamps. I would like to calculate the difference between value1 and value2, value 2 and value3 et cetera. How should I do this?
Asked
Active
Viewed 649 times
2 Answers
0
See: Javascript code to parse CSV data
Calculating time difference is merely subtracting them once you got the data into an array and parsed them as Number/long with parseInt.
0
Edited code snippet after reading comments. It seems that all differences in the data are 900 mSec, but this code should work for whatever other values.
Thing to note is that it assumes "high to low" ordering as seemingly present in the data.
var csv = [
'1374225300,126.0,1662.0,379.0,337.0,1091.0,893.0',
'1374224400,84.0,1491.0,251.0,289.0,909.0,801.0',
'1374223500,72.0,1200.0,126.0,180.0,651.0,682.0 ',
'1374222600,84.0,1011.0,126.0,180.0,505.0,563.0 ',
'1374221700,72.0,718.0,84.0,109.0,295.0,441.0 '
//... etcetera
];
function getPairDifference( pair ) {
//"pair" is a zero-based integer.
// "0" will return a difference between csv rows "0" & "1"
// "1" will return a difference between csv rows "1" & "2"
// etcetera...
var firstVal = parseInt( csv[pair].split(",")[0] );
var secondVal = parseInt( csv[pair + 1].split(",")[0] );
return firstVal - secondVal;
}
for ( var i = 0; i < csv.length; i += 1) {
// Demo code to visualize numbers.
// Actual function call of interest is simply "getPairDifference( i )"
$( "<div></div>" ).text( "DIFF "+i+": " + getPairDifference( i ) ).appendTo( "body" );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Ingmars
- 998
- 5
- 10
-
So I parsed the unix timestamp to a float. How should I continue now? I do not really understand the function above. Here is the relevant part of my code: for (var i=(csv.length-1); i>=0; i--) { var a = csv[i].split(","); var time = parseFloat(a[0]); – Samuel Van Ransbeeck Oct 13 '15 at 15:53
-
Could you add a couple of demo lines from your CSV data? It is hard to get the full picture without knowing the data structure. – Ingmars Oct 14 '15 at 06:23
-
Here you go: 1374225300,126.0,1662.0,379.0,337.0,1091.0,893.0 1374224400,84.0,1491.0,251.0,289.0,909.0,801.0 1374223500,72.0,1200.0,126.0,180.0,651.0,682.0 1374222600,84.0,1011.0,126.0,180.0,505.0,563.0 1374221700,72.0,718.0,84.0,109.0,295.0,441.0 1374220800,84.0,168.0,84.0,84.0,168.0,323.0 1374219900,42.0,109.0,42.0,72.0,84.0,214.0 1374219000,42.0,84.0,84.0,84.0,0.0,103.0 1374218100,3.0,72.0,42.0,36.0,0.0,53.0 1374217200,0.0,39.0,0.0,0.0,0.0,0.0 – Samuel Van Ransbeeck Oct 14 '15 at 08:58
-
I've edited my initial snippet to be more in-line with your data and existing loop. I hope it helps. – Ingmars Oct 14 '15 at 11:03