How to convert a string of numbers to an array of numbers in javascript?
- Admin
- Sep 20, 2023
- Javascript
This tutorial explains multiple ways the string contains numbers into an array of numbers for example. You can check my other post on Javascript check substring exists in a String
For example, a String contains numbers with delimiter
var strNumbers = "9,21,12,8";
The string contains numbers delimited by a comma.
And output
[ 9, 21, 12, 8 ]
How to convert a string to an array of numbers in javascript?
There are multiple ways.
- use the map array function First, the String of numbers is split using the split() function and returns a string of numbers.
Iterate the array using map() and convert the number using parseInt with base 10
let arrayNumbers = strNumbers.split(",").map(function (strNumber) {
return parseInt(strNumber, 10);
});
The same can be simplified using ES6 arrow functions
let arrayNumbers = strNumbers
.split(",")
.map((strNumber) => parseInt(strNumber, 10));
- use Array from function
use Array.from() function and with split array and number object.
Here is an example.
let array = Array.from(strNumbers.split(","), Number);
console.log(array);
Conclusion
In a summary, Multiple ways to convert a string of numbers into an array of numbers with examples.