Reputation: 51
I'm working with freecodecamp studies and need to find a way to turn a number into sum of positional digits like [1234] to [1000,200,30,4]. Code looks like this:
for(var i=0;i<newArr.length;i++){
var order = newArr.length-1 - i;
newArr.splice(i,1,newArr[i]*1e(order));
}
Here newArr will be 1234. Node gives error: invalid token 1e(order). Need some advice how to make it right.
Upvotes: 1
Views: 69
Reputation: 786
var a = 1234
b = []
while(a>0){
b.unshift(a%10 * (10 ** b.length))
a = parseInt(a/10)
}
console.log(b)
Upvotes: 1
Reputation: 1559
Number.prototype.padRight = function (n,str) {
return (this < 0 ? '-' : '') + (Math.abs(this)+ Array(n-String(Math.abs(this)).length+1).join(str||'0'));
}
var digits = "1234"
var tempCounter= digits.length;
var result=[];
for(var i=0;i<digits.length;i++,tempCounter--){
result.push(parseInt(digits[i]).padRight(tempCounter))
}
console.log(result);
Upvotes: 0
Reputation: 3782
I think you can use the below logic
var n = 123456;
n=n.toString();
var arr = n.split("");
var b = arr.map(function(x,i) {
return x * Math.pow(10, (arr.length-i-1));;
});
console.log(b);
Upvotes: 1