## Simple type conversion in arrays using map

·   ·  ☕ 1 min read

Type conversion is a big deal, but not anymore? Just use maps against a given array and them conversion shortcuts to simplify type conversion in Javascript.

Consider the below array -

 1  const nums = [1, 3, 5, 7, 9]; 

We can convert the type to string using a map.

 1 2 3 4  const nums = [1, 3, 5, 7, 9]; const numsStr = nums.map(val => String(val)); console.log("numsStr: ", numsStr); // [ '1', '3', '5', '7', '9' ] 

Since String by itself is a function, we can simplify the code further.

 1 2 3 4 5  const nums = [1, 3, 5, 7, 9]; const numsStr = nums.map(String); console.log(numsStr); // [ '1', '3', '5', '7', '9' ] 

Similarly, we can convert an array of strings to array of numbers.

Using concepts demonstrated earlier, we could have done -

 1 2 3 4 5 6  const numsStr = ["1", "3", "5", "7", "9"]; const nums = numsStr.map(Number); console.log(nums); // [ 1, 3, 5, 7, 9 ] 

.. and for Boolean type -

 1 2 3 4 5 6  const numsStr = ["1", "3", "5", "7", "9"]; const numsBool = numsStr.map(Boolean); console.log(numsBool); // [ true, true, true, true, true ] 

### Also see

Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things