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 converts a comma-separated values (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
const csv_to_array = (data, delimiter = ',', omitFirstRow = false) =>
  data
    .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
    .split('\n')
    .map(v => v.split(delimiter));

console.log(csv_to_array('a,b\nc,d')); 
console.log(csv_to_array('a;b\nc;d', ';')); 
console.log(csv_to_array('head1,head2\na,b\nc,d', ',', true));

Sample 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.



JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5])); 
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));

Output:

[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]