How to convert an array of digits to a number in Node.js

1 Answer

0 votes
// ------------------------------------------------------------
// digitsToNumberJoin
// Converts an array of digits into a number by joining them.
// Example: [1,2,3,4] → "1234" → 1234
// ------------------------------------------------------------
function digitsToNumberJoin(digits) {
  return Number(digits.join(""));
}

// ------------------------------------------------------------
// digitsToNumberMath
// Pure mathematical folding (no string operations).
// Example: [1,2,3,4] → (((1*10)+2)*10+3)*10+4
// ------------------------------------------------------------
function digitsToNumberMath(digits) {
  let n = 0;
  
  for (const d of digits) {
    n = n * 10 + d;
  }
  
  return n;
}

// ------------------------------------------------------------
// Main
// ------------------------------------------------------------
const digits = [4, 6, 3, 0, 9, 1, 2];

console.log("Using join():", digitsToNumberJoin(digits));
console.log("Using math():", digitsToNumberMath(digits));



/*
run:

Using join(): 4630912
Using math(): 4630912

*/

 



answered Sep 22, 2022 by avibootz
edited 2 days ago by avibootz
...