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

## Find out how you can convert an integer to an array 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 would need to 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)); // output: [-1, 2, 3, 4, 5]
console.log(numToArray(12345)); // output: [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 would need to follow these steps:

1. Convert the number to a string;
2. Convert string to an array of numeric string characters using `String.prototype.split()`;
3. Convert each array item to an integer by passing `Number` as an argument to `Array.prototype.map()`.
```// ES6+
function numToArray(num) {
// 1: convert number to string
const numStr = String(num);
// 2: convert string to array of numeric strings
const arr = numStr.split('');
// 3: convert each array item to an integer
return arr.map((digit) => {
// convert to integer
const num = Number(digit);
// if result is `NaN` add original value as string, otherwise add integer
return isNaN(num) ? digit : num;
});
}

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: convert number to string
const numStr = String(num);
// 2: convert string to array of numeric strings, and;
// 3: convert each array item to an integer
return Array.from(numStr, (digit) => {
// convert to integer
const num = Number(digit);
// if result is `NaN` add original value as string, otherwise add integer
return isNaN(num) ? digit : num;
});
}

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

## Add a Leading Digit to Represent the Sign

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 [1, 1, 2, 3, 4, 5]
```

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

1. Convert the number to a string;
2. Check if the first element of array is the negative sign;
3. Add `0` or `1` for the sign as the first element of the new array;
4. 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: convert number to string
const numericStr = String(num);
// 2: is first element minus sign?
const hasSign = numericStr === '-';
// 3: add 0 or 1 as first element in array
const numbersArr = [Number(hasSign)];

// 4: 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]
```

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

1. Convert the number to a string;
2. Convert string to an array of numeric string characters using `String.prototype.split()`;
3. Check, remove and remember if the first element of array is the negative sign;
4. Convert each array item to an integer by passing `Number` as an argument to `Array.prototype.map()`;
5. Use `Array.prototype.unshift()` to add the leading digit for the sign to the front of the array.
```function numToArray(num) {
// 1: convert number to string
const numStr = String(num);
// 2: convert string to array of numeric strings
const arr = numStr.split('');
// 3: is first element minus sign?
const hasSign = arr === '-';
if (hasSign) {
// remove minus sign from array
arr.shift();
}

// 4: convert each array item to an integer
const intArr = arr.map(Number);
// 5: 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]
```

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

1. Convert the number to a string;
2. Check, and remember, if the numeric string starts with the negative sign;
3. Convert string to an array of numeric strings using a regular expression (that only adds digits, ignoring any sign) with `String.prototype.match()`;
4. 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;
5. 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 `[]`
const arr = Array.isArray(strArr) ? strArr.map(Number) : [];
// 5: add 0 or 1 as first element in array and all other digits after
return [ Number(hasSign), ...arr ];
}

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

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