EN
JavaScript - convert a string of numbers to an array of numbers
0
points
In this article, we would like to show you how to convert a string of numbers to an array of numbers in JavaScript.
Quick solution (ES6):
// ONLINE-RUNNER:browser;
const string = '1,2,3,4';
const result = string.split(',').map((item) => parseInt(item, 10));
console.log(result); // [ 1, 2, 3, 4 ]
Practical example
In this example, we use split() method to split string into an array of strings by a comma separator (','). Then we use map() method with parseInt() to convert the array of strings into an array of numbers.
// ONLINE-RUNNER:browser;
var string = '1,2,3,4';
var result = string.split(',').map(function(item) {
return parseInt(item, 10);
});
console.log(result); // [ 1, 2, 3, 4 ]
console.log(typeof result[0]); // number