Categories
JavaScript Answers

How to Convert a String of Numbers to an Array of Numbers in JavaScript?

Spread the love

Sometimes, we have a string with a comma-separated list of numbers that we want to convert to an array of numbers.

In this article, we’ll look at how to convert a string of numbers to an array of numbers in JavaScript.

Using String and Array Methods

We can use the split method available with JavaScript strings to convert a string into an array of strings by splitting the string by a separator.

So we can use the split method to split the string into an array of strings by the commas.

So it’ll return an array of strings with the stuff between the commas.

Then we can call the array map method to map the split string array entries into numbers.

For instance, we can write:

const nums = "1,2,3,4".split(`,`).map(x => +x)
console.log(nums)

We call split with the comma to separate the string into an array with the number strings in it.

Then we call map with a callback that converts each entry to a number with the unary + operator.

Therefore, nums is [1, 2, 3, 4] as a result.

Instead of using the unary + operator, we can also use the parseInt function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseInt(x, 10))
console.log(nums)

parseInt takes 2 arguments.

The first argument is the value we want to convert to a number.

The 2nd argument is the base that we want the returned number to be in.

So 10 would convert x to a decimal number.

Therefore, we get the same result as before.

Another way to convert the strings to numbers is to use the Number function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => Number(x))
console.log(nums)

and we get the same thing.

Number always convert to decimal numbers so we don’t have to specify it.

There’s also the parseFloat function that converts a value to a floating-point number if we want to do that.

It takes the same argument as parseInt .

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseFloat(x, 10))
console.log(nums)

And we get the same result as before for nums .

Conclusion

We can convert a string of numbers to an array of numbers with some string, array and number functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *