0

I have done this in C# before, but I don't have a clue how to do that in javascript.

What I want to do:

while (/*Is not the last line of the csv file*/)
 {
    var text = /* read the line */
    var split = /* array with the values from the line that was read */

    alert(split[0]);
}

Thank you for your suggestions!

ThePat02
  • 27
  • 1
  • 1
  • 6
  • 1
    Possible duplicate of [NodeJs reading csv file](https://stackoverflow.com/questions/23080413/nodejs-reading-csv-file) – Hassan Imam Mar 04 '18 at 18:03

1 Answers1

1

Is your CSV file stored somewhere? Or do you have it stored as a string?

To follow your structure, here is a plunker: https://plnkr.co/edit/dCQ4HRz3mCTkjFYrkVVA?p=preview

var csv = 
`data1,data2,data3
col1,col2,col3`;
var lines = csv.split("\n");
while( typeof lines[0] !== "undefined" ){
    var line = lines.shift();
    var split = line.split(',');
    document.querySelector("#content").innerHTML += split[0]+"<br/>";
}

If you haven't got the CSV as a string, depending on if you are using Node to read a file or JavaScript in the browser to read an uploaded file, you need other code to convert that. Or you may use a library.

You may have to handle trimming of spaces around commas by modifying the code above.

By the way, instead of creating temporary variables, some may prefer not using a while-loop: https://plnkr.co/edit/31yMTw9RepdW1cF8I6qj?p=preview

document.querySelector("#content").innerHTML = 
csv.split("\n")        // these are lines
  .map(                // map those lines, 1 line to ...
    l => l.split(",")  // to 1 array
  ).map(
    a => a[0]+"<br/>"  // and map those arrays 1 array to the string
  ).join('');            // and join them to become 1 string

You may find those array manipulating functions interesting, like map(), filter(), reduce().

Hope these help!

Sunny Pun
  • 726
  • 5
  • 14
  • I have my csv file stored online or at a specific path. How to I read it to a string? – ThePat02 Mar 04 '18 at 18:26
  • As a quick example, I use `fetch()` (note this is async) and then convert it to `text()` then use the text (say for `console.log()`) like this: `fetch("http://insight.dev.schoolwires.com/HelpAssets/C2Assets/C2Files/C2ImportUsersSample.csv").then(a => a.text() ).then(t=>console.log(t));` – Sunny Pun Mar 04 '18 at 18:40
  • And in case of your first example, how do I put it in your "csv" variable? – ThePat02 Mar 04 '18 at 18:44
  • Instead, as `fetch()` is async, we have to put the code inside the last `then()`. So it'll be like `.then(t=>{ var csv=t; ... })` and the code inside the `{}` block will be run only when the `t` is ready. – Sunny Pun Mar 04 '18 at 18:46
  • @ThePat02 Does it work? If it helped, please consider voting up and marking this answer as correct. Thank you. – Sunny Pun Mar 08 '18 at 17:09