How to Convert an Integer to an Array of Digits in JavaScript?

Converting positive integers to an array of digits is fairly straightforward. However, the complication arises with negative integers, specifically in how you add the negative sign (`-`) to the resulting array. For example, following are a few options:

Make the Most Significant Digit Negative

Making the most significant digit negative means that in the resulting array, if the original number is negative, the first digit will have the negative sign:

```// -12345 becomes [-1, 2, 3, 4, 5]
```

To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps:

1. Convert the number to a string;
2. Convert string to an array of numeric strings using a regular expression with `String.prototype.match()`;
3. Return empty array when no match is found (i.e. when `String.prototype.match()` returns `null`). Otherwise, use `Array.prototype.map()` to convert each array item to an integer, by passing `Number` as an argument to it.
```// ES6+
function numToArray(num) {
// 1: convert number to string
// 2: use regex to match '-' (optionally) and numbers
const strArr = String(num).match(/-?\d/g);
// 3: if match found, convert each item to an integer, else return `[]`
return Array.isArray(strArr) ? strArr.map(Number) : [];
}

console.log(numToArray(12345)); // [1, 2, 3, 4, 5]
console.log(numToArray(-12345)); // [-1, 2, 3, 4, 5]
```

Following are a few examples of the return values from this function when string values are passed in:

```console.log(numToArray('foo')); // []
console.log(numToArray('12345')); // [1, 2, 3, 4, 5]
console.log(numToArray('-12345')); // [-1, 2, 3, 4, 5]
```

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

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 to an array of integers. If you don't do that, then you will get "`Uncaught TypeError: Cannot read property 'map' of null`" error.

Add the Minus Sign as a String

Adding the minus sign (`-`) as a string means that in the resulting array, if the original number is negative, the first element of the array will have the minus sign as a string:

```// -12345 becomes ['-', 1, 2, 3, 4, 5]
```

To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps:

1. Check if value is a number (or a numeric string);
2. Convert the number to a string;
3. Convert string to an array of numeric string characters using `String.prototype.split()`;
4. Use `Array.prototype.map()` to iterate over each array item and convert each numeric string to a number using `Number`, and check for `'-'` explicitly (to add it as is).
```// ES6+
function numToArray(num) {
// 1: check if number (or numeric string)
if (isNaN(Number(num))) {
return [];
}

// 2: convert number to string
const numStr = String(num);
// 3: convert string to array of numeric strings
const arr = numStr.split('');
// 4: convert each array item to an integer (and add '-' as is if present)
return arr.map((digit) => (digit === '-') ? '-' : Number(digit));
}

console.log(numToArray(12345)); // [1, 2, 3, 4, 5]
console.log(numToArray(-12345)); // ['-', 1, 2, 3, 4, 5]
```

Following are a few examples of the return values from this function when string values are passed in:

```console.log(numToArray('foo')); // []
console.log(numToArray('12345')); // [1, 2, 3, 4, 5]
console.log(numToArray('-12345')); // ['-', 1, 2, 3, 4, 5]
```

You can also rewrite this using the `Array.from()` method which would help you combine the step related to using `String.prototype.split()` and `Array.prototype.map()` (as the first argument to `Array.from()` is split into an array, and the second argument is called on every element of the array):

```// ES6+
function numToArray(num) {
// 1: check if number (or numeric string)
if (isNaN(Number(num))) {
return [];
}

// 2: convert number to string
const numStr = String(num);
// 3: convert string to array of numeric strings, and;
// 4: convert each array item to an integer (and add '-' as is if present)
return Array.from(numStr, (digit) => (digit === '-') ? '-' : Number(digit));
}

console.log(numToArray(12345)); // [1, 2, 3, 4, 5]
console.log(numToArray(-12345)); // ['-', 1, 2, 3, 4, 5]
```

Following are a few examples of the return values from this function when string values are passed in:

```console.log(numToArray('foo')); // []
console.log(numToArray('12345')); // [1, 2, 3, 4, 5]
console.log(numToArray('-12345')); // ['-', 1, 2, 3, 4, 5]
```

Adding a leading digit to represent the sign means that in the resulting array, the first element can be used to represent the sign (i.e. `0` for positive integers and `1` for negative integers):

```// 12345 becomes [0, 1, 1, 2, 3, 4, 5]
// -12345 becomes [1, 1, 2, 3, 4, 5]
```

To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps:

1. Check if value is a number (or a numeric string);
2. Convert the number to a string;
3. Check if the first element of array is the negative sign;
4. Add `0` or `1` for the sign as the first element of the new array;
5. Loop over each character in the string, converting each one to an integer, and adding it to the new array one by one.
```// ES6+
function numToArray(num) {
// 1: check if number (or numeric string)
if (isNaN(Number(num))) {
return [];
}

// 2: convert number to string
const numericStr = String(num);
// 3: is first element minus sign?
const hasSign = numericStr[0] === '-';
// 4: add 0 or 1 as first element in array
const numbersArr = [Number(hasSign)];

// 5: convert and add each string character as an integer to array
for (let i = Number(hasSign); i < numericStr.length; i++) {
numbersArr.push(parseInt(numericStr[i], 10));
}

return numbersArr;
}

console.log(numToArray(12345)); // [0, 1, 2, 3, 4, 5]
console.log(numToArray(-12345)); // [1, 1, 2, 3, 4, 5]
```

Following are a few examples of the return values from this function when string values are passed in:

```console.log(numToArray('foo')); // []
console.log(numToArray('12345')); // [0, 1, 2, 3, 4, 5]
console.log(numToArray('-12345')); // [1, 1, 2, 3, 4, 5]
```

As an alternative, you can achieve the same result in the following way as well:

1. Check if value is a number (or a numeric string);
2. Convert the number to a string;
3. Convert string to an array of numeric string characters using `String.prototype.split()`;
4. Check, remove and remember if the first element of array is the negative sign;
5. Convert each array item to an integer by passing `Number` as an argument to `Array.prototype.map()`;
6. Use `Array.prototype.unshift()` to add the leading digit for the sign to the front of the array.
```function numToArray(num) {
// 1: check if number (or numeric string)
if (isNaN(Number(num))) {
return [];
}

// 2: convert number to string
const numStr = String(num);
// 3: convert string to array of numeric strings
const arr = numStr.split('');
// 4: is first element minus sign?
const hasSign = arr[0] === '-';
if (hasSign) {
// remove minus sign from array
arr.shift();
}

// 5: convert each array item to an integer
const intArr = arr.map(Number);
// 6: add 0 or 1 as first element in array
intArr.unshift(Number(hasSign));

return intArr;
}

console.log(numToArray(12345)); // [0, 1, 2, 3, 4, 5]
console.log(numToArray(-12345)); // [1, 1, 2, 3, 4, 5]
```

Following are a few examples of the return values from this function when string values are passed in:

```console.log(numToArray('foo')); // []
console.log(numToArray('12345')); // [0, 1, 2, 3, 4, 5]
console.log(numToArray('-12345')); // [1, 1, 2, 3, 4, 5]
```

Another way of achieving the same result would be to follow these steps:

1. Check if value is a number (or a numeric string);
2. Convert the number to a string;
3. Check, and remember, if the numeric string starts with the negative sign;
4. Convert string to an array of numeric strings using a regular expression (that only adds digits, ignoring any sign) with `String.prototype.match()`;
5. Return empty array when no match is found (i.e. when `String.prototype.match()` returns `null`). Otherwise, use `Array.prototype.map()` to convert each array item to an integer, by passing `Number` as an argument to it;
6. Add the sign as the first number in the array, and right after add all the digits.
```// ES6+
function numToArray(num) {
// 1: convert number to string
const numericStr = String(num);
// 2: string starts with minus sign?
const hasSign = numericStr.startsWith('-');
// 3: use regex to match only numbers
const strArr = numericStr.match(/\d/g);
// 4: if match found, convert each item to an integer, else return `[]`
// 5: add 0 or 1 as first element in array and all other digits after
return Array.isArray(strArr) ? [ Number(hasSign), ...strArr.map(Number) ] : [];
}

console.log(numToArray(12345)); // output: [0, 1, 2, 3, 4, 5]
console.log(numToArray(-12345)); // output: [1, 1, 2, 3, 4, 5]
```

Following are a few examples of the return values from this function when string values are passed in:

```console.log(numToArray('foo')); // []
console.log(numToArray('12345')); // [0, 1, 2, 3, 4, 5]
console.log(numToArray('-12345')); // [1, 1, 2, 3, 4, 5]
```

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.