0

I'm getting large numbers as input and want to display them with a small space for every step of thousand (every 3 digits). So I'm looking for an array of max. three digits as output.

Examples:

Input: 10       Output: [10]
Input: 1234     Output: [1, 234]
Input: 24521280 Output: [23, 521, 280]

It does not matter if the output array contains strings or numbers.

What would be a most elegant (comprehensive / short) solution in Javascript ES6?


I wrote two working solutions, but I feel that they are overly complicated or that I'm missing something:

Solution 1)

function numberToThreeDigitArray(number) {
  if (number / 1000 < 1) return [number];

  return [
    ...numberToThreeDigitArray(Math.floor(number / 1000)),
    number % 1000
  ];
}

Solution 2)

function numberToThreeDigitArray(number) {
  return number.toString().split('').reverse().map((char, i) => {
    return i !== 0 && i % 3 === 0
      ? ' ' + char
      : char;
  }).join('').split('').reverse().join('').split(' ');
}
kadrian
  • 4,761
  • 8
  • 39
  • 61
  • 3
    The thing you're missing is that formatting a number according to the user's locale is a solved problem: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Jamiec Nov 10 '16 at 17:23
  • `number.toLocaleString().split(",").map(x => parseInt(x));` – halfo Nov 10 '16 at 17:31
  • @Jamiec Aaah!! The solution with the regex was what I was looking for – kadrian Nov 10 '16 at 17:33
  • @kadrian you're not looking for the regexp solution. it's junk. – Mulan Nov 10 '16 at 18:04
  • 1
    @halfo don't use `parseInt` without a radix. And why not just `.map(Number)`? – Mulan Nov 10 '16 at 18:04

1 Answers1

0

number.toLocaleString().split(',').map(num => +num) should do it for you.

See the toLocaleString MDN docs.

Example:

const arr = (24521280).toLocaleString().split(',').map(num => +num)

// [24, 521, 280]

// or

function getNumber(n) {
  return n.toLocaleString().split(',').map(num => +num)
}
Josh Beam
  • 19,292
  • 3
  • 45
  • 68