Since there's no convenience method to convert an integer into an array of integers, perhaps, the easiest way is to simply:
- Convert the integer into a numeric string;
- Convert the numeric string into an array of integers.
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 "
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));
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:
Array.from()expects the first argument to either be an iterable object or an array-like object (i.e. objects with a
lengthproperty and indexed elements) — criteria that
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
Please note that primitive strings can be passed as the first argument to
String object internally. This may help you understand why the result of "
Number.prototype.toString()" (which yields a primitive string) also works with
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]
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.