How to Convert JavaScript CSV to Array

When you are working with an external dataset, then you probably find that the data is in the CSV format, and somehow you need to convert it into an array for processing. Converting array to csv and csv to array is one of the most valuable operations in JavaScript. So let’s see how to convert a csv string into an array.

JavaScript CSV to Array

To convert CSV to Array in JavaScript, use the string.split() method. The split() is a built-in JavaScript 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, to use for splitting the string.
limit

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

Return value

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

Example

Let’s define a string containing comma-separated values and convert it into an array using the split() method.

let str = "Tokyo,Nairobi,Berlin,Oslo,Moscow"

let arr = str.split(",")

console.log(arr)

Output

['Tokyo', 'Nairobi', 'Berlin', 'Oslo', 'Moscow']

You can see in the output that the CSV string is converted into an array.

That’s it for this tutorial.

See also

JavaScript array to set

JavaScript array to object

JavaScript array to json

Leave a Comment