How to convert a 2D array to a CSV string in JavaScript?

The CSV (Comma Separated Values) file format is a popular way of exchanging data between applications and data stores. The CSV file format is simple and easy to understand, and many applications and programming languages support it.

In JavaScript, there are several ways to convert a 2D array into a CSV string. In this tutorial, we'll look at effective methods: using Array.map() with join(), and a manual approach for handling special cases.

Using Array.map() with join() (Recommended)

The most straightforward approach is to use Array.map() to process each row and join() to combine elements with commas.

Example

<html>
<head>
    <title>Convert 2D Array to CSV</title>
</head>
<body>
    <h2>2D Array to CSV Conversion</h2>
    <div id="result"></div>
    <script>
        var data = [
            ["Name", "Age", "City"],
            ["John", "30", "New York"],
            ["Jane", "40", "London"],
            ["Bob", "25", "Paris"]
        ];
        
        // Convert 2D array to CSV string
        var csvString = data.map(row => row.join(',')).join('<br>');
        
        document.getElementById("result").innerHTML = "<pre>" + csvString + "</pre>";
    </script>
</body>
</html>
Name,Age,City
John,30,New York
Jane,40,London
Bob,25,Paris

Handling Special Characters

When CSV data contains commas, quotes, or newlines, values need to be wrapped in double quotes and internal quotes must be escaped.

<html>
<head>
    <title>CSV with Special Characters</title>
</head>
<body>
    <h2>CSV with Special Characters</h2>
    <div id="result"></div>
    <script>
        var data = [
            ["Name", "Description", "Price"],
            ["Product A", "High-quality, durable item", "29.99"],
            ["Product B", "Contains "quotes" and, commas", "15.50"]
        ];
        
        function escapeCSVField(field) {
            // Convert to string and check if escaping is needed
            var str = String(field);
            if (str.includes(',') || str.includes('"') || str.includes('<br>')) {
                // Escape double quotes by doubling them, then wrap in quotes
                return '"' + str.replace(/"/g, '""') + '"';
            }
            return str;
        }
        
        function arrayToCSV(array) {
            return array.map(row => 
                row.map(field => escapeCSVField(field)).join(',')
            ).join('<br>');
        }
        
        var csvString = arrayToCSV(data);
        document.getElementById("result").innerHTML = "<pre>" + csvString + "</pre>";
    </script>
</body>
</html>
Name,Description,Price
Product A,"High-quality, durable item",29.99
Product B,"Contains ""quotes"" and, commas",15.50

Comparison of Methods

Method Simplicity Handles Special Characters Performance
map() + join() High No Fast
Custom escaping function Medium Yes Fast
JSON.stringify approach Low Limited Slower

Complete Utility Function

<html>
<head>
    <title>Complete CSV Converter</title>
</head>
<body>
    <h2>Complete CSV Converter Function</h2>
    <div id="result"></div>
    <script>
        function convertToCSV(array, delimiter = ',') {
            if (!Array.isArray(array) || array.length === 0) {
                return '';
            }
            
            function escapeField(field) {
                var str = String(field);
                if (str.includes(delimiter) || str.includes('"') || str.includes('<br>')) {
                    return '"' + str.replace(/"/g, '""') + '"';
                }
                return str;
            }
            
            return array.map(row => 
                row.map(field => escapeField(field)).join(delimiter)
            ).join('<br>');
        }
        
        // Test with various data types
        var testData = [
            ["ID", "Name", "Active", "Score"],
            [1, "Alice", true, 95.5],
            [2, "Bob, Jr.", false, 87.2],
            [3, "Carol "CJ" Smith", true, 92.0]
        ];
        
        var csv = convertToCSV(testData);
        document.getElementById("result").innerHTML = "<pre>" + csv + "</pre>";
    </script>
</body>
</html>
ID,Name,Active,Score
1,Alice,true,95.5
2,"Bob, Jr.",false,87.2
3,"Carol ""CJ"" Smith",true,92

Conclusion

Use Array.map() with join() for simple 2D array to CSV conversion. For production applications handling user data, implement proper CSV escaping to handle commas, quotes, and newlines correctly.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements