{

How to convert a string of numbers to an array of numbers in javascript?


This tutorial explains multiple ways the string contains numbers into an array of numbers for example.

For example, Strign contains numbers with delimemter

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 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.