How to Convert an Integer Into an Array of Integers in JavaScript?

Find out how you can convert an integer to an array in JavaScript

Since there's no convenience method to convert an integer into an array of integers, perhaps, the easiest way is to simply:

  1. Convert the integer into a numeric string;
  2. Convert the numeric string into an array of integers.

While there are many ways of converting an integer to a string in JavaScript, we recommend using the Number.prototype.toString() or the String object for clarity and readability.

Converting Positive Integers Into an Array

The following would convert a positive integer into an array of numeric strings:

const num = 12345;
const numStr = (typeof num === 'number') ? String(num) : '';
const arr = numStr.split('');

console.log(arr); // output: ['1', '2', '3', '4', '5']

If the value of the variable that holds the integer value can be non-numeric (such as null, etc.) then it is important to add a check such as typeof num === 'number' to ensure that we only convert integers to string. The reason for this is to avoid bugs such as "String(null)" where null would literally be converted into string "null" and this can lead to unwanted bugs.

To convert the array of numeric strings from the last example into an array of integers we need to ensure that every element of the resulting array is an integer. To do that, we can for example, use map() in the following way:

const intArr = arr.map((digit) => Number(digit));

console.log(intArr); // output: [1, 2, 3, 4, 5]

We can, of course, refactor this and simply pass the Number object to map() as well. For example:

const intArr = arr.map(Number);

console.log(intArr); // output: [1, 2, 3, 4, 5]

The reason this works is because it is equivalent to the following:

arr.map((str, index, arr) => Number(str, index, arr));

The Number object ignores the second and third arguments passed in by map() and only accepts the first argument. This is the reason why map(Number) works and can be a nice shortcut.

Now that we have got this far, we can refactor our code even further using Array.from() like so:

const num = 12345;
const numStr = (typeof num === 'number') ? String(num) : '';
const intArr = Array.from(numStr, Number);

console.log(intArr); // output: [1, 2, 3, 4, 5]

The reason this works is because:

  1. Array.from() expects the first argument to either be an iterable object or an array-like object (i.e. objects with a length property and indexed elements) — criteria that String object fulfils;
  2. Array.from() allows an optional map() function as a second argument (which is called on every element of the array) to which we simply pass the Number object.

Please note that primitive strings can be passed as the first argument to Array.from() as well because JavaScript automatically converts them to the String object internally. This may help you understand why the result of "Number.prototype.toString()" (which yields a primitive string) also works with Array.from().

Converting Negative Integers Into an Array

So far, whatever we discussed in the previous topic works only for positive integers. To account for both negative and positive integers, we can use a regular expression like so:

const num = -12345;
const strArr = String(num).match(/-?\d/g);
const intArr = Array.isArray(strArr) ? strArr.map(Number) : [];

console.log(strArr); // output: ['-1', '2', '3', '4', '5']
console.log(intArr); // output: [-1, 2, 3, 4, 5]

Since the match() method returns null on failure and an array of all matches on success, it is important to check whether the result is indeed an array before using map(Number) to convert the array of numeric string into an array of integers. Otherwise, you will get an error saying, "Uncaught TypeError: Cannot read property 'map' of null".

Please note that the g flag used with match is important here because it returns all results matching the regular expression.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.