
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting string to an array in JavaScript
Suppose we have a special kind of string like this −
const str ="Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";
We are required to write a JavaScript function that converts the above string into the following array, using the String.prototype.split() method −
const arr = [ { "Integer":1, "Float":2.0 }, { "Boolean":true, "Integer":6 }, { "Float":3.66, "Boolean":false } ];
We have to use the following rules for conversion −
\n marks the end of an object
one whitespace terminates one key/value pair within an object
',' one comma separates the key from value of an object
Therefore, let’s write the code for this function −
Example
The code for this will be −
const str ="Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False"; const stringToArray = str => { const strArr = str.split('\n'); return strArr.map(el => { const elArr = el.split(' '); return elArr.map(elm => { const [key, value] = elm.split(','); return{ [key]: value }; }); }); }; console.log(stringToArray(str));
Output
The output in the console will be −
[ [ { Integer: '1' }, { Float: '2.0' } ], [ { Boolean: 'True' }, { Integer: '6' } ], [ { Float: '3.66' }, { Boolean: 'False' } ] ]
- Related Questions & Answers
- Converting multi-dimensional array to string in JavaScript
- Converting array to phone number string in JavaScript
- Converting array of objects to an object in JavaScript
- Converting a JavaScript object to an array of values - JavaScript
- Converting string to a binary string - JavaScript
- Converting array to set in JavaScript
- Converting array of arrays into an object in JavaScript
- Converting string to MORSE code in JavaScript
- Converting whitespace string to url in JavaScript
- Converting array of objects to an object of objects in JavaScript
- Converting a string to a date in JavaScript
- JavaScript: Converting a CSV string file to a 2D array of objects
- Converting object to 2-D array in JavaScript
- Converting a comma separated string to separate arrays within an object JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
Advertisements