Split a Number into an Array in JavaScript


Borislav Hadzhiev

Wed Oct 20 20212 min read


Photo by Joshua Earle

Split a Number into an Array #

To split a number into an array, call the Array.from() method, passing it the number converted to a string as the first parameter and the Number object as the second - Array.from(String(number), Number). The Array.from method creates a new array from an iterable, such as a string.

const number = 1234; const arrOfDigits = Array.from(String(number), Number); console.log(arrOfDigits); // 👉️ [1, 2, 3, 4]

The first parameter we passed to the Array.from method is an iterable object we want to convert into an array.

We had to convert our number into a string because numbers are not iterable.

// 👇️ ['1', '2', '3', '4'] console.log(Array.from(String(1234)));

At this point we have an array of strings. To convert each string into a number we use the second parameter of the Array.from method.

The second parameter the method takes is an Array.map function.

This function gets called with each element in the array. We want to convert each element into a number, so we make use of the Number object.

Here is the same example, however this time we explicitly use the map function instead of passing it as a second parameter to Array.from.

const number = 1234; // 👇️ ['1', '2', '3', '4'] const arrOfStr = Array.from(String(number)); const arrOfNum = arrOfStr.map(str => Number(str)); console.log(arrOfNum); // 👉️ [1, 2, 3, 4]

The map function gets called with each string in the array and we simply convert the string to a number and return it.

The Array.from method is not supported in Internet Explorer. If you have to support the browser, use the String.split method instead.

To split a number into an array:

  1. Convert the number to a string.
  2. Call the split() method on the string to get an array of strings.
  3. Call the map() method on the array to convert each string to a number.
// Supported in IE const number = 1234; const arr = String(number) .split('') .map(str => Number(str)); console.log(arr); // 👉️ [1, 2, 3, 4]

After we converted our number to a string, we used the String.split method. The method divides a string into an array of strings, based on a provided separator.

const number = 1234; // 👇️ ['1', '2', '3' ,'4'] console.log(String(number).split(''));
We pass an empty string as the separator to the split method, because we want to split on each digit.

The last step is the same as in the previous approach - we have to convert each string to a number, using the map method.

The function we passed to the map method gets invoked with each element in the array, we convert it to a number and return it straight away.

This is the approach you want to use if you have to support Internet Explorer.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.