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(' ');
}