CONTEXT
I am trying to save an array to a text file.
My array is a js variable arrR
(say):
[-0, 0.0016, 0.0034, 0.005, 0.0067, 0.0082, 0.0103, 0.0116, 0.0135, 0.0154, 0.017]
The function below saves the array in a text file:
JavaScript
x
14
14
1
$("#saveB").click(function () {
2
var diff = 3;
3
var json = JSON.stringify(arrR);
4
var downloadLink = document.createElement("a");
5
var blob = new Blob(["ufeff", json]);
6
var url = URL.createObjectURL(blob);
7
downloadLink.href = url;
8
downloadLink.download = "data.txt";
9
document.body.appendChild(downloadLink);
10
downloadLink.click();
11
document.body.removeChild(downloadLink);
12
arrR=[];
13
});
14
And this works nicely.
WHAT I WOULD LIKE TO DO
Instead of having a .txt file like:
[-0, 0.0016, 0.0034, 0.005, 0.0067, 0.0082, 0.0103, 0.0116, 0.0135, 0.0154, 0.017]
I would like to have a .txt or a.csv file, which would like:
JavaScript
1
13
13
1
data measured at xx
2
0; -0
3
3; 0.0016
4
6; 0.0034
5
9; 0.005
6
12;0.0067
7
15; 0.0082
8
18;0.0103
9
21; 0.0116
10
24; 0.0135
11
27; 0.0154
12
30; 0.017
13
where:
the second column of the file is arrR
,
the first column is an array where all elements are 0,3,6 (the difference being diff
) ,
the header is the current time.
Is there a simple way to do it ?
Many thanks
Advertisement
Answer
You could change the
JavaScript
1
2
1
var json = JSON.stringify(arrR);
2
to
JavaScript
1
4
1
const header = `data measured at ${(new Date()).toUTCString()}n`
2
var json = header + arrR.map((value, index) =>
3
`${diff*index}; ${value}`).join('n');
4