How to Convert CSV to Array in JavaScript

To convert CSV to Array in JavaScript, you can use the “string.split()” method. The split() is a built-in String function that splits a provided string into an array of strings by separating it into substrings using a separator provided in the argument.

Syntax

string.split(separator, limit)

Parameters

Arguments Value
separator The separator argument is used to specify the character or the regular expression for splitting the string.
limit

The limit argument is the upper limit on the number of splits in the given string.

Return value

The split() method returns an array of strings formed at each position where the separator occurs.

Steps

  1. Split the CSV string into rows using the newline character as a delimiter.
  2. Iterate through each row and split it into individual values using the comma character as a delimiter.
  3. Add the resulting arrays of values to the final array.

Code example

function csvToArray(csv) {
  const rows = csv.split('\n');
  const result = [];

  for (const row of rows) {
    const values = row.split(',');
    result.push(values);
  }

  return result;
}

const csvString = 'Name,Age,Occupation\nKeval Shah,30,Developer\nEsha Shah,25,Designer';

const array = csvToArray(csvString);
console.log(array);

Output

[
  [ 'Name', 'Age', 'Occupation' ],
  [ 'Keval Shah', '30', 'Developer' ],
  [ 'Esha Shah', '25', 'Designer' ]
]

If you need to parse more complex CSV data, consider using a dedicated CSV parsing library like Papa Parse that can handle these cases correctly.

Leave a Comment