JS&TS
May 15, 2024
How to cast an array
Here you'll see how to cast an array of strings to array of numbers in an easy way.
Prelude:
From time to time you need to convert an array of strings into array of numbers, but fortunetly JS has a solution for you:
const arrStrings = ['12', '12.4', '20', '2.1']; const arrNumbers = [14, 2.3, 19, 22.2]; console.log(arrStrings.map(Number)); // [12, 12.4, 20, 2.1]; console.log(arrNumbers.map(String)); // ['14', '2.3', '19', '22.2'];
const arr = ['12', 0, 1, '', []]; console.log(arr.map(Boolean)); // [true, false, true, false, true];
Conclusion:
In case if you need to cast array of some types in another types you can use map
with built-in types like String
, Number
and Boolean
as well.