Computer >> Computer tutorials >  >> Programming >> Javascript

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' } ]
]