Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Joshua Earle
To convert a string to array of numbers:
split()
method on the string, to get an array of strings.map()
method to iterate over the array and convert each string to
number.map
method will return a new array, that contains only numbers.const str = '5,15,45'; // 👇️ ['5', '15', '45'] const arrOfStr = str.split(','); const arrOfNum = arrOfStr.map(element => { return Number(element); }); console.log(arrOfNum); // 👉️ [5, 15, 45]
The only parameter we passed to the String.split method is a separator.
const str = '5 15 45'; // 👇️ ['5', '15', '45'] console.log(str.split(' '));
split
method.const str = '5-15-45'; // 👇️ ['5', '15', '45'] console.log(str.split('-'));
The final step is to call the Array.map method on the array of strings.
The function we passed to the map
method gets called with each element
(string) in the array.
On each iteration, we convert the string into a number and return the result.
map
method returns a new array that contains only the values that the function returned - in our case all the numbers.If your string contains numbers that end with characters, e.g. 15a
, you have
to use the parseInt
method.
const str = '5a,15b,45c'; // 👇️ ['5a', '15b', '45c'] const arrOfStr = str.split(','); const arrOfNum = arrOfStr.map(element => { return parseInt(element, 10); }); console.log(arrOfNum); // 👉️ [5, 15, 45]
Because our numbers end with a character, we can't pass them straight to the
Number
object. Instead, we use the
parseInt
method to extract the numbers.
We pass the following parameters to the parseInt
method:
10
, so we have to explicitly specify itNote that this approach only works if the number precedes the characters, it
wouldn't work if you had a string like a15,b30
.