tubos
tubos

Reputation: 99

Extracting individual data from a string

Snippet of code doesnt work properly:

<script>
var singledata = [];
var txt = "141112,15:00,22.5\n141112,16:00,22.6\n141112,17:00,22.7\n";
var lines = txt.split("\n");
for (var i=0; i<lines.length; i++) {
   singledata.push( [lines.split(',')] );
}
console.log(lines);
console.log(singledata[0]);
</script>

the txt string will normally come from a text file

I would like to get an array with following data:

singledata = [[141112,15:00,22.5],[141112,16:00,22.6],[141112,17:00,22.7]];

This is an example normally the data file could contain > 1000 lines. So i would like to avoid having to use an array for the lines and then another one with the same data but split up.

Upvotes: 0

Views: 27

Answers (1)

Barmar
Barmar

Reputation: 782785

It should be:

singledata.push( lines[i].split(',') );

lines is the whole array, lines[i] is the current element in the iteration.

You don't need [] around lines[i].split(','). split returns an array, you were wrapping another around around it for no reason.

var singledata = [];
var txt = "141112,15:00,22.5\n141112,16:00,22.6\n141112,17:00,22.7\n";
var lines = txt.split("\n");
for (var i=0; i<lines.length; i++) {
   singledata.push( lines[i].split(',') );
}
console.log(lines);
console.log(singledata[0]);

Upvotes: 2

Related Questions