1

I have been experimenting with this code http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/ to get data from a text file. (Working demo here: http://mounirmesselmeni.github.io/html-fileapi/).

It works well for reading files, but I am stumped about how to get the data into an array. It seems as though it is reading everything into the "lines" array, but I can't work out how to use it.

I tried modifying it like this:

function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
var myArray = [];                      
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(','));   //put data into myArray
}

function myFunction() {                          //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
    text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}

but that didn't work. I know I am missing something simple here, but this has me stumped.

2 Answers 2

1

Currently you modify the array twice:

lines.push(allTextLines.shift().split(','));     // shift modifies the array
myArray.push(allTextLines.shift().split(','));   //gets the shifted array

You might want to try putting this in temp variable:

var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);
Sign up to request clarification or add additional context in comments.

Comments

0

Try

csv.split(/\r\n|\n|,/).map(function(value, index) {
  demo.innerHTML += "\n" + value.trim()
});

var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',

    demo = document.getElementById("demo");

csv.split(/\r\n|\n|,/).map(function(value, index) {
  demo.innerHTML += "\n" + value.trim()
})
<div id="demo"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.