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 -
const nums = [ 1 , 3 , 5 , 7 , 9 ];
We can convert the type to string using a map .
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.
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 -
const numsStr = [ "1" , "3" , "5" , "7" , "9" ];
const nums = numsStr . map ( Number );
console . log ( nums );
// [ 1, 3, 5, 7, 9 ]
.. and for Boolean
type -
const numsStr = [ "1" , "3" , "5" , "7" , "9" ];
const numsBool = numsStr . map ( Boolean );
console . log ( numsBool );
// [ true, true, true, true, true ]
Also see