Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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));

about 4 years ago · Juan Pablo Isaza Relatório

0

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));

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda