Languages
[Edit]
EN

JavaScript - convert a string of numbers to an array of numbers

0 points
Created by:
Anisha-Kidd
682

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

 

See also

  1. JavaScript - get all numbers in string and push them to array

References

  1. String.prototype.split() - JavaScript | MDN
  2. Array.prototype.map() - JavaScript | MDN
  3. parseInt() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join