DEV Community

Discussion on: Get all separate digits of a number (TypeScript)

Collapse
 
brense profile image
Rense Bakker • Edited

Wouldnt it be easier to convert the number to a string and just split it? Performance-wise it doesnt make much difference.

function separateDigits(num: number) : number[] {
  const numAsString = num + ''
  const strings = numAsString.split('')
  return strings.map(s => Number(s))
}

const numArr = separateDigits(1443643)
console.log(numArr)
Enter fullscreen mode Exit fullscreen mode

benchmark: jsben.ch/67w9k

Collapse
 
amarok24 profile image
Jan Prazak

Thanks for the jsbench link, seems to be a very usefuly online tool, I will save that.
And about the different solution with toString conversion, yes, why not, if you prefer type conversion and the map method. They are definitely many solutions to the same problem.