Sunday, July 18, 2021

Junior Developer Central JS Practice Exercise - 18

 
Question: 

Write a Javascript program to convert a comma-separated values (CSV) string to a 2D array. A new line indicates a new row in the array. 

for eg. 

Input: 

const oldString = `abc,def,ghi
jkl, mno, pqr
stu, vwx, yza`;

Output: 

0: (3) ["abc", " def", " ghi"]
1: (3) ["jkl", " mno", " pqr"]
2: (3) ["stu", " vwx", " yza"]




Answer: 

function createArr(str) {

  return str.split('\n').map(row => row.split(','));

}




> we declare a variable 'createArr' 
> it has one parameter 'str' 
> to explain this function, we shall use the input example in the question above 'oldString'
> we first split the 'str' with the split () method that will return an array of substrings
> the split ('\n') method will return a new array which will have three items 
> each of these items is a row from the 'oldString' mentioned above
>> so after split ('\n) we get 
>> 0: ["abc, def, ghi"]
>> 1: ["jkl, mno, pqr"]
>> 2: ["stu, vwx, yza"]
> but we need a 2 dimensional array 
> so we need to split each of the values, in the row, into an array itself
>> like this: 
>> 0: ["abc", " def", " ghi"]
>> 1: ["jkl", " mno", " pqr"]
>> 2: ["stu", " vwx", " yza"]
> in order to further split each of the values into an array itself we use the map() method
> the map() method creates a new array with the results of calling a function for every array element
> the map() method calls the provided function once for each element in an array 
> our aim is to further split the row elements we have, into an array itself 
> so we use the map () method and call a function, that will be called on each value of the 'row' 
> so we will use the split () method on each values of the 'row' and split them by the 'comma'
> like this .map(row => row.split(',')
> this will be a one line code and we shall return the same

No comments:

Post a Comment