0

Can someone tell me how can I store the values of the CSV file into an array that I am retrieving from the web server.

Data example:

Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100

Suppose I have the following scenario shown below:

var url1 = 'path for CSV file'
$.get(url1, function(data) {
    // data param contains all the data that I retrieved from the csv
});

using the above example, how can I store my data into an array so the end result looks like the following:

enter image description here

enter image description here

2
  • data is a single string with all your csv content? var rows = data.split("\n") then loop through rows and split on , - but that's not all a "csv" is. You should also check for / parse for " and "". Commented Feb 24, 2021 at 17:10
  • I'd be surprised if nothing here can help you: stackoverflow.com/… Commented Feb 24, 2021 at 17:11

2 Answers 2

1

A very straight forward approach:

  1. Split into lines on \n
  2. Split each line ,

const csv = `Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100`;

const result = csv.split("\n").map(l=>l.split(','));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

Use a reducer (Array.reduce):

// create an array of arrays
const csvLines = `Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100`
  .split("\n")
  .map(v => v.split(","));

// bonus: to array of objects
let headers = csvLines.shift();
const fromCsv = csvLines.reduce( (acc, val) => [...acc, {
      [headers[0]]: parseFloat(val[0]),
      [headers[1]]: parseFloat(val[1]),
      [headers[2]]: parseFloat(val[2]) } ], []);
      
console.log(fromCsv);

1 Comment

That isn't the result to OP requested. (although it is most appropriate :-) )

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.