'Get from one number an array of numbers without brackets
Need to receive:
digitize(12345) -> [5,4,3,2,1]
I wrote a code:
function digitize(n) {
let arr = Array.from(n + '');
return arr.reverse();
}
console.log(digitize(12345));
Output: [ '5', '4', '3', '2', '1' ]
This is very close, but this is showing an array of strings. How can I get an array of numbers (without the quotes), instead?
Solution 1:[1]
You could map (the second parameter of Array.from) with Number.
This approach works only for positive integers which are equal or less than Number.MAX_SAFE_INTEGER (9007199254740991).
function digitize(n) {
return Array
.from(n.toString(), Number)
.reverse();
}
console.log(digitize(12345));
Solution 2:[2]
You could consider a recursive function, and do it without conversion to string:
function digitize(n) {
return n < 10 ? [n] : [n % 10, ...digitize(Math.floor(n / 10))];
}
console.log(digitize(12345));
Solution 3:[3]
I would not go the "hacky", buggy and presumably less efficient route over stringification here:
function digitize(n) {
const digits = [];
while (n >= 1) {
digits.push(n % 10);
n = Math.floor(n / 10);
}
return digits;
}
or using a do-while depending if you want digitize(0) to be [0] instead of []:
function digitize(n) {
const digits = [];
do {
digits.push(n % 10);
n = Math.floor(n / 10);
} while (n >= 1)
return digits;
}
this will still fail for some large floats due to precision issues though.
Solution 4:[4]
Try
// The following function would give you an array of numbers in descending order of the digits of a number given as an argument to the function
function digitize(n) {
const str = n.toString();
const myArr = str.split("");
const reversedArr = myArr.map(function (x) {
return parseInt(x, 10);
}).sort((a,b)=>{return b-a});
return reversedArr
}
console.log(digitize(12345))
console.log(digitize(45343))
console.log(digitize(484643))
// [5, 4, 3, 2, 1]
// [5, 4, 4, 3, 3]
// [8, 6, 4, 4, 4, 3]
// The following function would give you an array of numbers in reversed order of the digits of a number given as an argument to the function
function digitize(n) {
const str = n.toString();
const myArr = str.split("");
const reversedArr = myArr.map(function (x) {
return parseInt(x, 10);
}).reverse();
return reversedArr
}
console.log(digitize(12345));
console.log(digitize(45343));
console.log(digitize(484643));
// [5, 4, 3, 2, 1]
// [3, 4, 3, 5, 4]
// [3, 4, 6, 4, 8, 4]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | trincot |
| Solution 3 | |
| Solution 4 |
