I need a function that, given a number, say, 123, will output an array [100,20,3]. I've tried something like this (borrowed from another question on SO):
function separateNumberIntoUnits(n) {
var arr = [];
var i = 10;
while (n > i / 10)
{
arr.unshift(n % i - n % (i / 10));
i *= 10;
}
return arr;
}
and it works for all numbers except for 10, 100 etc. I've tried to figure out what's going on, but math isn't my strong side...
If there's a more efficient way to do this, feel free to write your own solution.
I think this is the most efficient way:
function separateNumberIntoUnits(n) {
if (n == 0) return [0];
// n = Math.floor(n); // needed for decimal numbers
var arr = [];
var i = 1;
while (n > 0) {
arr.unshift((n % 10) * i);
n = Math.floor(n / 10);
i *= 10
}
return arr;
}
document.writeln(separateNumberIntoUnits(1234) + "<br />")
document.writeln(separateNumberIntoUnits(100) + "<br />")
document.writeln(separateNumberIntoUnits(10) + "<br />")
document.writeln(separateNumberIntoUnits(1) + "<br />")
document.writeln(separateNumberIntoUnits(0) + "<br />")
unshift is the best way to do it: Array.unshift vs Array.push and Array.reverse: https://jsperf.com/array-unshift-vs-array-push-and-array-reverse
You could treat the number as a string.
Split it into an array of its digits, then map each digit to its decimal place by multiplying by the appropriate power of 10:
function separateNumberIntoUnits(n) {
var s= n.toString().split('');
return s.map(function(digit, n) {
return digit * Math.pow(10, s.length - n - 1);
});
}
document.body.innerHTML=
separateNumberIntoUnits(1234) + '<br>' +
separateNumberIntoUnits(100) + '<br>' +
separateNumberIntoUnits(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With