How to Read a CSV File into a 2D Array in JavaScript

Converting a CSV File Into a 2D Array

Real answer: Use Papa Parse . Save yourself the hassle of escaped/quoted fields, fields with delimiters in them, variations in the CSV format, etc...

The "do it yourself" way: csvStr.split("\n").map(function(row){return row.split(",");})

read .csv file into 2D-array

You don't need 2 loops in while loop, here is the solution.

public class array2D
{
private static int[][] readArrayFromFile(String filename)
{
int[][] array = new int[9][9];
try
{
Scanner myFileReader = new Scanner(new File(filename));

int i = 0;
while (myFileReader.hasNextLine())
{

String line = myFileReader.nextLine();
String[] tokens = line.split(";");

for (int j = 0; j < tokens.length; j++)
{
array[i][j] = Integer.parseInt(tokens[j]);
}
i++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
return array;
}

private static void printArray(int[][] inputArray)
{
for (int y = 0; y < inputArray.length; y++)
{
for (int x = 0; x < inputArray[y].length; x++)
{
System.out.print(inputArray[y][x] + "\t");
}
System.out.println();
}
System.out.println();
}

public static void main(String[] args)
{
String filename = "./src/test.csv";
int[][] sudokuField = readArrayFromFile(filename);
printArray(sudokuField);
}
}

Combine multiple CSV files into one 2D array

One way to do this is to use Promise.all. It takes an array of promises and calls a single callback when all of them have resolved. So you could restructure the retrieve/parse part of your code like this:

var filenames = ["/projectUCF/SN00.csv", "/projectUCF/SN01.csv"];
var promises = [];

// create array of promises, one per file, that resolve after the file is retrieved a resolve with the parsed data
filenames.forEach(function (filename) {
promises.push(new Promise(function (resolve, reject) {
$.get(filename, function (csvString) {
var fileData = $.csv.toArrays(csvString, { onParseValue: $.csv.hooks.castToScalar });
var removeRows = 1;
while (removeRows--) {
fileData.shift();
}
resolve(fileData);
});
}));
});

// wait until all files have been retrieved, then continue
Promise.all(promises).then(function (results) {
var arrayData = [];
results.forEach(function (fileData) {
arrayData.push(...fileData);
});

// remaining code goes here
});

How do you convert a CSV file into a 2d array in a .js file?

You have to open your csv file, then read the lines and write them in your js file.

Basically:

-> Open csv file

-> Create js file

-> Write 'var variable1 = [' in your js file

-> Iterate on csv lines

-> Write them in your js file

-> Write '];' in your js file

-> Close the files

In python:

myJSFile = open('Path_to_your_js_file', 'w')
myJSFile.write("var variable1 = [\n")

myCSVFile = open('Path_to_your_csv_file', 'r')
for line in myCSVFile .readlines() :
myJSFile.write("[%s],\n" % line.strip())

myJSFile.write("];")

myJSFile.close()
myCSVFile.close()

That should do the work ;)

How to read the contents of a CSV file and put it into a 2D array in Java?

Before parsing your data into a 2D array, your code loops through a 1D array of the data, each eventual row separated by dashes. When you get to the for-loop, your code views the dash as an 8th column in the line read2DString[read2DStringIndex][g] = fromfile[g], as g would represent an index of 7. Only afterward does your code increment the row. To solve this, you would want to put the if-statement before this line and then use "continue;" to skip to the next iteration of the loop to bypass this problem.

You also have to reset the columns to 0 when you increment the row so instead of
read2DString[read2DStringIndex][g] = fromfile[g]
, use read2DString[read2DStringIndex][g%8] = fromfile[g]. The modulus operator (%) will give you the remainder after division, which in this case is the correct column number after dividing out the length of completed rows worth of columns.

Reading CSV file into an array in Java [incompatible types: Integer cannot be converted to int[].]

1. Dealing with this error: Integer cannot be converted to int[]

We can only assign int[] to an int[], lines is a List of Integer and so when we try to get any element in lines it will always return an Integer.

So int thirdCountry[] = lines.get(3); basically means int[] = some int value and that's what causes the above issue. So inorder to fix it I declared lines like this ArrayList<String[]> lines.

2. Now, why the List is of String[] type?

Since the data can be a String, int, or a double, it is safe to have a String[] which would accept all three.

3. Blind rule while getting any element from an Array or Collection

Whenever you are trying to get some element from an array or collection, always check the length or size and that index should be less than the length of the same.

public static void main(String[] args) throws IOException {
System.out.println("Data from CSV file to be analysed:"+"\n");
String file = "jrc-covid-19-all-days-of-world_ASSIGNMENT-FIXED.csv";
ArrayList<String[]> lines = new ArrayList<String[]>();
String line = null;

try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
int i = 0;
while(((line = bufferedReader.readLine()) != null) && i<27) {
lines.add(line.split(","));
System.out.println(Arrays.toString(lines.get(i)));
i++;
}
}
catch (IOException e) {
e.printStackTrace();
}

if(lines.size() > 3) {
String thirdCountry[] = lines.get(3);

if(thirdCountry.length > 6) {
String cp3 = thirdCountry[6];
System.out.println(cp3);
}
}

}

4. Adding numbers

For adding we need to convert the String values to numeric values (int, long, or double). Let's say we are converting to int, so the sample values can be "123", "abc", "abc123", or "" (an empty string). So you can try like this

String s1 = "";
int total = 0;
try {
total += Integer.parseInt(s1);
} catch (NumberFormatException e) {
System.out.println("Not a number!");
}
System.out.println(total);

You can modify this for long and double as per your comfort.

How to parse a .csv file into a multidimensional array in PHP?

You did pretty good. You can look at fgetcsv documentation for more. I would have change you function so it will get the argument as input (try avoid using global)

// insert data
function writeInList($user_entry, $path ) {
$file = fopen($path ,"a");
fputcsv($file, $user_entry, ",");
fclose($file);
}

//extract data
function getList($path, $limit = 100000) {
$file = fopen($path, "r");
if (!$file) return null; // or throw error or print to log
$allRows = []; //
while (($data = fgetcsv($file, $limit, ",")) !== FALSE) {
$allRows[] = $data; // as fgetcsv return array already exlode by ","
}
fclose($file);
return $allRows;
}

Now you have 2-Dim array return from getList. Use is as getList("todo.csv") and display as you pleased.

Hope that helps!



Related Topics



Leave a reply



Submit