In JavaScript, converting a 2D array into a CSV (Comma-Separated Values) string is a common requirement when exporting data or generating text-based files.
Problem Statement
Given a 2D array, convert it into a CSV-formatted string where:
- Each row becomes a new line.
- Each element in a row is separated by a comma.
Input:
[ [ "a" , "b"] , [ "c" ,"d" ] ]Output:
a,b
c,dInput:
[ [ "1", "2"] ["3", "4"] ["5", "6"] ]Output:
1,2
3,4
5,6JavaScript Methods Used
To achieve this, we must know some array prototype functions which will be helpful in this regard:
1. Join function: The Array.prototype.join( ) function is used to join all the strings in an array with a character/string.
[ "a","b"].join( ",") will result in : "a,b"2. Map function: The Array.prototype.map() returns a new array with the results of calling a function that we provide, on each element.
arr= ["a","b"]
// Adding "c" to each element
newArray = arr.map( item => item + "c")
value of newArray = ["ac", "bc"][Approach 1]: Using map() and join()
This method converts a 2D array into a CSV string using map() and join().
- Uses map() to turn each 1D row into a comma-separated string.
- Uses join("\n") to merge all rows into the final CSV format.
Here, we will be using the map() and join() functions to convert the CSV values to strings.
// Create CSV file data in an array
var array2D = [
[ "a" , "2"] ,
[ "c" ,"d" ]
];
// Use map function to traverse on each row
var csv = array2D
.map((item) => {
// Here item refers to a row in that 2D array
var row = item;
// Now join the elements of row with "," using join function
return row.join(",");
}) // At this point we have an array of strings
.join("\n");
// Join the array of strings with "\n"
console.log(csv);
Output:
a,2
c,d- Create a 2D array and use map() to process each inner array as a row.
- Convert each row into a comma-separated string using join(","), resulting in an array of CSV rows.
- Combine all rows with join("\n") and log the final CSV string to the console.
[Approach 2]: Using for Loops
We can even use for loops to traverse in the array, instead of a map.
- Iterate through rows and elements manually.
- Append commas between elements.
- Add a newline after each row.
Here , we will be using the javascript loops to convert the CSV to strings.
var csv="";
//create CSV file data in an array
var array2D = [
[ "a" , "2"] ,
[ "c" ,"d" ]
];
for (var index1 in array2D) {
var row = array2D[index1];
var string = "";
// Traversing each element in the row
for (var index in row) {
var w = row[index];
// Adding the element at index "index" to the string
string += w;
if (index != row.length - 1) {
// If the element is not the last element , then add a comma
string += ",";
}
}
string += "\n";
// adding the string to the final string "csv"
csv += string;
}
console.log(csv);
Output
a,2 c,d
- Initialize an empty string csv and iterate over each row of the 2D array using a for...in loop.
- Build each row by looping through its elements, appending values and commas (except after the last element).
- Add a newline after each row, append it to csv, and log the final CSV string to the console.
[Approach 3]: Using reduce()
Another approach to convert a 2D array to a CSV string is to use the Array.prototype.reduce() method.
- Use the reduce() method to iterate over each row of the 2D array.
- Inside the reduce() callback function, use the join() method to concatenate the elements of each row with a comma.
- Append a newline character \n after each row.
- Concatenate the result strings of each row iteration.
// Create CSV file data in an array
var array2D = [
[ "a" , "2"] ,
[ "c" ,"d" ]
];
var csv = array2D.reduce((acc, row) => {
// Join elements of the row with comma separator
let rowString = row.join(",");
// Add a newline character after each row
rowString += "\n";
// Concatenate the result strings of each row iteration
return acc + rowString;
}, "");
console.log(csv);
Output
a,2 c,d
- Create a 2D array and use reduce() with an empty string accumulator to build the CSV output.
- Convert each row into a comma-separated string using join(",") and append a newline character.
- Concatenate all rows into a single CSV string and log the result to the console.
Note: This approach simplifies the code by combining the iteration and string concatenation logic within the reduce() method, resulting in concise and readable code.