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

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

In JavaScript, you can convert an array of digits to an integer (within the range of Number.MAX_SAFE_INTEGER) in the following ways:

For numbers beyond the Number.MAX_SAFE_INTEGER, you can convert the array of digits to a bigint value instead of an integer.

Looping, Shifting and Adding Digits to the Right

To convert an array of digits to an integer, you can use the Array.prototype.reduce() method, in the following way:

// ES5+
array.reduce(function (accum, digit) {
    return (accum * 10) + digit
}, 0);

Passing 0 as the second argument to Array.prototype.reduce() is needed to set the value the accumulator is initialized to (when the callback is called for the first time). This is important as without it a "TypeError: Reduce of empty array with no initial value" error would be thrown for empty arrays.

This works in the following way:

  • An "accumulated" value is passed to the callback (as the first argument), which contains the result of the calculation of previous iteration (or the initial value "0" at start);
  • By multiplying the "accumulated" value by 10, each value in the array is widened to the right, to which then the current digit is added. This results in each digit in the array being added to the resulting integer one by one;
  • At the end of the iteration, the final (single/reduced) value of accumulator is returned.

For example:

// ES6+
const digits = [1, 2, 3, 4, 5];
const int = digits.reduce((accum, digit) => (accum * 10) + digit, 0);

console.log(int); // 12345

You can rewrite the callback to Array.prototype.reduce() without arrow function to make it compatible with ES5.

This can be visualized like so:

// Iteration#1 (accum = 0, digit = 1) => (0 * 10) + 1 = 1
// Iteration#2 (accum = 1, digit = 2) => (1 * 10) + 2 = 12
// Iteration#3 (accum = 12, digit = 3) => (12 * 10) + 3 = 123
// Iteration#4 (accum = 123, digit = 4) => (123 * 10) + 4 = 1234
// Iteration#5 (accum = 1234, digit = 5) => (1234 * 10) + 5 = 12345
// => 12345

Convert Array to String and Then to Integer

You can use the Array.prototype.join() method to convert an array to a string, and then call Number() wrapper to convert the resulting string to an integer:

const digits = [1, 2, 3, 4, 5];
const int = Number(digits.join(''));

console.log(int); // 12345

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