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

javascript array string to array number convert examples

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)


In a summary, Multiple ways to convert a string of numbers into an array of numbers with examples.

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
You'll get a notification every time a post gets published here.