0

I have a CSV which contains files like

kilo;1; kome;3; hell;5; 

I want all numbers to be stored in an int array(JS)

var lines = content.split("\r"); for (var i = 0; i < lines.length; i++) { var x = lines[i].split(";"); } var A = [x[3]]; 

It saves each element as a different array!

3
  • Some more information would be nice how it's not really clear how your csv looks like. Commented Oct 21, 2017 at 16:35
  • Please show all relevant code. What is lines and count? What are expected results? Take a few minutes to read How to Ask and minimal reproducible example Commented Oct 21, 2017 at 16:37
  • @charlietfl true I thanks Commented Oct 21, 2017 at 16:54

2 Answers 2

3

First of all, you are referencing count in your for loop, but that doesn't exist and needs to be i instead. Also, you are populating your array after the loop, with only the latest value of x.

Here you can see a slightly changed working example:

var csv = "kilo;1;\r\nkome;3;\r\nhell;5;", lines = csv.split("\r\n"), myIntArray = []; for (var i = 0; i < lines.length; i++) { var fields = lines[i].split(";"); myIntArray.push(parseInt(fields[1], 10)); } console.log(myIntArray);

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

1 Comment

and a question what does that 10 mean?
2

var lines = ["kilo;1;", "kome;3;", "hell;5;"] var numbers = lines.map(line => +line.split(";")[1]) console.log(numbers)

or you can get all numbers from the string at once:

var CSV = "kilo;1;\r\nkome;3;\r\nhell;5;" var numbers = CSV.match(/[0-9]+/g) console.log(numbers)


to sort, something like:

var lines = ["kilo;1;", "kome;3;", "hell;5;"] var result = lines.map(line => line.split(";")).sort((a, b) => a[1] - b[1]) console.log(result)


As a side note, there are many table libraries like https://datatables.net/ that have sorting options:

var lines = ["kilo;1;", "kome;3;", "hell;5;"] var data = lines.map(line => line.split(';')) $('#example').DataTable( { data: data, columns: [ { title: "a" }, { title: "b" } ], order: [ 1, "asc" ], // order by column 2 in ascending order searching: false, paging: false, info: false, } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/> <table id="example" class="display compact"/>

2 Comments

The first one can it reorder the words based on the numbers ex var lines = ["kilo;5;", "kome;1;", "hell;3;"] to output kome hell kilo?
Slai take a look at an important question:[stackoverflow.com/questions/46861439/reorder-csv-r‌​ows]