How can I convert a JavaScript array to a CSV string with custom column headers?
Davide S
davide s profile pic

To convert a JavaScript array to a CSV string with custom column headers, you can follow these steps: 1. Define the array of data: Start by defining your array of data. Each element of the array represents a row in the resulting CSV string. Each row should be an array where each element represents a value in a column. 2. Define the column headers: Create an array that contains the custom column headers. The order of the column headers should match the order of the values in each row. 3. Generate the CSV string: - Create an empty array to store each row of the CSV. - Push the column headers as the first row of the CSV array. - Iterate over each row of data: - Create an empty array to store the values of the current row. - Iterate over each value in the row: - Convert the value to a string and handle any necessary formatting (e.g., enclosing values in quotes if they contain special characters). - Push the formatted value to the row array. - Push the row array to the CSV array. - Join the elements of each row with a comma to create a CSV string. - Join the rows with newline characters to separate them in the final CSV string. Here's an example implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

function convertArrayToCSV(data, headers) {
  const csv = [];
  
  // Add the column headers
  csv.push(headers.join(','));

  // Iterate over each row of data
  for (const row of data) {
    const rowValues = [];

    // Iterate over each value in the row
    for (const value of row) {
      // Convert the value to a string and handle any necessary formatting
      const formattedValue = typeof value === 'string' && value.includes(',')
        ? `"${value}"`
        : String(value);

      rowValues.push(formattedValue);
    }

    // Push the row values to the CSV array
    csv.push(rowValues.join(','));
  }

  // Join the rows with newline characters
  return csv.join('\n');
}

// Example usage
const data = [
  ['John', 'Doe', 25],
  ['Jane', 'Smith', 30],
  ['Mark', 'Johnson', 40]
];
const headers = ['First Name', 'Last Name', 'Age'];

const csvString = convertArrayToCSV(data, headers);
console.log(csvString);

This will produce the following CSV string:

First Name,Last Name,Age John,Doe,25 Jane,Smith,30 Mark,Johnson,40

TheconvertArrayToCSV() function takes the data array and column headers as parameters and returns the resulting CSV string. It handles special characters by enclosing values in quotes and separates values with commas.