Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get from one number an array of numbers without brackets

Need to receive:

digitize(12345) -> [5,4,3,2,1]

I wrote a code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading