w3resource

JavaScript: Converts a comma-separated values string to a 2D array

JavaScript fundamental (ES6 Syntax): Exercise-3 with Solution

Write a JavaScript program to convert a comma-separated value (CSV) string to a 2D array.

Note: Use String.split('\n') to create a string for each row, then String.split(delimiter) to separate the values in each row. Omit the second argument, delimiter, to use a default delimiter of ,. Omit the third argument, omitFirstRow, to include the first row (title row) of the CSV string.

  • Use Array.prototype.slice() and Array.prototype.indexOf('\n') to remove the first row (title row) if omitFirstRow is true.
  • Use String.prototype.split('\n') to create a string for each row, then String.prototype.split(delimiter) to separate the values in each row.
  • Omit the second argument, delimiter, to use a default delimiter of ,.
  • Omit the third argument, omitFirstRow, to include the first row (title row) of the CSV string.

Sample Solution:

JavaScript Code:

// Source: https://bit.ly/2neWfJ2

// Define a function called `csv_to_array` that converts CSV data to an array.
const csv_to_array = (data, delimiter = ',', omitFirstRow = false) =>
  // Split the CSV data by newline characters, map each row to an array of values split by the delimiter.
  data
    .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
    .split('\n')
    .map(v => v.split(delimiter));

// Test cases
console.log(csv_to_array('a,b\nc,d')); // [['a', 'b'], ['c', 'd']]
console.log(csv_to_array('a;b\nc;d', ';')); // [['a', 'b'], ['c', 'd']]
console.log(csv_to_array('head1,head2\na,b\nc,d', ',', true)); // [['a', 'b'], ['c', 'd']]

Output:

[["a","b"],["c","d"]]
[["a","b"],["c","d"]]
[["a","b"],["c","d"]]

Flowchart:

flowchart: Converts a comma-separated values string to a 2D array

Live Demo:

See the Pen javascript-basic-exercise-1-3 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to copy a string to the clipboard.
Next: Write a JavaScript program to convert a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-3.php