Split a Number into an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Split a Number into an Array #

To split a number into an array:

  1. Convert the number to a string.
  2. Use the Array.from() method to convert the string into an array of digits.
  3. Use the map() function to convert each string in the array to a number.
index.js
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 that we want to convert to an array.

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

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

At this point we have an array of strings. We used the second parameter of the Array.from method to convert each string to a number.

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

The 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 an example that explicitly uses the Array.map() method.

index.js
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 method gets called with each string in the array.

On each iteration, we convert the current element to a number and return the result.

Alternatively, you can use the String.split() method.

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.
index.js
// Supported in IE const number = 1234; const arr = String(number) .split('') .map(str => Number(str)); console.log(arr); // 👉️ [1, 2, 3, 4]

We converted the number to a string and used the String.split method.

The method splits a string into an array based on the provided separator.

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

Lastly, we used the map() method to convert each string to a number.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.