0

Is it possible to convert csv data with this format:

    date,value1,value2,value3//CSV header
    2015-11-04,58,221,12//second row csv
    2015-11-05,62,234,18
    2015-11-06,69,258,22
...

to this format?

[12,18,22,...]//Get the data from value3 field

The web references I have seen converts csv file to array, but not into the same format i have written above.

Thanks in advance.

2
  • Do it in two steps; 1. importing the CSV (framework), 2. selecting the column you want (regular multidimensional arrays). Commented Dec 3, 2015 at 11:37
  • Thank you for your comment. I am new into programming so first i will search your option and then i will apply step by step. Commented Dec 3, 2015 at 14:16

2 Answers 2

1
var rows = data.split("\n");
var array = [];
var final = [];

$.get("csvstring.php", function(data) {
    $.each(rows, function(index, value){
        if(index > 0) {
            var values = value.split(",");
            array.push(values);
        }
    });

    $.each(array, function(index, value){
        $.each(value, function(indexs, values) {
          console.log(index);
          if(indexs == 3) {
            final.push(values);
          }
        });
    });
});

console.log(final);

This returns:

["12", "18", "22"]

I hope it helped!

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

5 Comments

And if the csv data were a file with unlimited rows(data.csv)?,first i must to parse it?.
What do you mean? This will do with any amount of rows!
When i put a csv file: ` var CSV = "data.csv"` instead data like the example ` var CSV = "2015-11-04,58,221,12\n2015-11-05,62,234,18\n2015-11-06,69,258,22"` i get in console: 0 csvstring.php:26 //and [] csvstring.php:33 the csv file is the same like question
Then combining both methods.Thanks.
Works great. The final step to get the object is remove the first element,in this case "value3":["value3","12","18","22",...] to ["12","18","22",...].
0

You can load it by using $.get and parse it using .split(), here's a little example.

$.get("YOUR.csv", function(data){
  var yourParsedCSV = data.split("\n").map(function(i){return i.split(",")});
});

Heres what it does, explained

1º split rows with

data.split("\n");

2º loop rows and return them as arrays splitting by commas ( .map is the fastest option)

...map(function(i){ //for every item in the previous array...
  return i.split(","); //return it as array
});

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.