A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format.
In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript.
Given a comma-separated values (CSV) string to a 2D array, using Javascript function.
Input: 'Name,Roll Number\nRohan,01\nAryan,02'
Output: [
{Name: "Rohan", Roll Number: "01"},
{Name: "Aryan", Roll Number: "02"}
]
// With delimiter ;
Input: 'Name;Roll Number\nRohan;01\nAryan;02'
Output: [
{Name: "Rohan", Roll Number: "01"},
{Name: "Aryan", Roll Number: "02"}
]
We must know some array and string prototype functions that will be helpful in this regard.
indexOf function: The String.prototype.indexOf() function finds the index of the first occurrence of the argument string in the given string and the value returned is in the 0-based index.
Example:
str = 'How\nare\nyou?'
str.indexOf('\n');
Output:
3
Slice function: The Array.prototype.slice() method returns a new array containing a portion of the array on which it is implemented and the original array remains the same.
Example:
['a','b','c','d'].slice(1)
Output:
['b','c','d']
Map function: The Array.prototype.map() method returns a new array with the results of calling a provided function on every element.
Example:
arr = [2, 4, 8, 16]
// Dividing each element of the array by 2
newArr = arr.map( item => item/2)
Output:
[1, 2, 4, 8]
Split function: The String.prototype.split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.
Example:
str = "Geeks for Geeks"
// Split the array when ' ' is located
arr = str.split(' ');
Output:
[ 'Geeks', 'for', 'Geeks' ]
Reduce function: The Array.prototype.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each element of the array from left to right and the return value of the function is stored in an accumulator.
Example:
arr = [2,4,6,8]
// Here 0 is the initial value of the accumulator
// while traversing, currentValue has been added
arr.reduce(function(accumulator,currentValue){
return accumulator+currentValue;
},0)
Output:
20
Approach:
- The JavaScript string slice() method extracts parts of a string and returns the extracted parts in a new string taking ‘\n’ as the first occurrence.
- Data Values are stored using “\n” as the delimiter.
- JavaScript map() function will iterate over all values of the title values array and append each object at the end of the array
- The “storeKeyValue” variable is used to store each key with its respective values.
Example: In this example, we will convert a comma-separated value (CSV) to a javascript array using the slice(), map(), split(), and reduce() methods of Javascript.
Javascript
<script>
function CSVstring_to_Array(data, delimiter = ',' ) {
const titles = data.slice(0, data
.indexOf( '\n' )).split(delimiter);
const titleValues = data.slice(data
.indexOf( '\n' ) + 1).split( '\n' );
const ansArray = titleValues.map( function (v) {
const values = v.split(delimiter);
const storeKeyValue = titles.reduce(
function (obj, title, index) {
obj[title] = values[index];
return obj;
}, {});
return storeKeyValue;
});
return ansArray;
};
var inputString1 = "Name,Roll Number\nRohan,01\nAryan,02" ;
console.log(CSVstring_to_Array(inputString1));
var inputString2 = "Name;Roll Number\nRohan;01\nAryan;02" ;
console.log(CSVstring_to_Array(inputString2, ';' ));
</script>
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!