Skip to content
Advertisement

How to add a column to 1d json array and save it to a file?

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:

$("#saveB").click(function () {
var diff  = 3;
var json = JSON.stringify(arrR);
var downloadLink = document.createElement("a");
var blob = new Blob(["ufeff", json]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "data.txt";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
arrR=[];
});

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:

data measured at xx
0; -0
3; 0.0016
6; 0.0034
9; 0.005
12;0.0067
15; 0.0082
18;0.0103
21; 0.0116
24; 0.0135
27; 0.0154
30; 0.017

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

var json = JSON.stringify(arrR);

to

const header = `data measured at ${(new Date()).toUTCString()}n`
var json = header + arrR.map((value, index) =>
       `${diff*index}; ${value}`).join('n');
Advertisement