Categories
JavaScript Answers

How to Convert a JavaScript String into an Array of Integers?

Spread the love

Sometimes, we want to convert a JavaScript string into an array of integers.

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

Convert a JavaScript String into an Array of Integers

To convert a JavaScript string into an array of integers, we can use the JavaScript string’s split method with the array filter method to keep only the numbers.

Then we call map with Number to convert all the values into numbers.

For instance, we can write:

const str = "5 6 7 69 foo"
const intArray = str.split(" ").map(Number).filter(Boolean);
console.log(intArray)

We have the str string which we want to extract the numbers from and put them into the array.

To do that, we call split with a space string to split the string by its spaces and put the split strings into an array.

Then we call map with Number to convert all the values into numbers.

Then we call filter to filter the items that aren’t numbers.

NaN is falsy so any value that can’t be converted to numbers is filtered out.

Therefore, intArray is:

[5, 6, 7, 69]

Conclusion

To convert a JavaScript string into an array of integers, we can use the JavaScript string’s split method with the array filter method to keep only the numbers.

Then we call map with Number to convert all the values into numbers.

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 *