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

136
Visualizações
ParseInt a string to numbers in an array

I'm trying to convert a string of numbers into an array of elements with each number. I thought parseInt would convert the string to numbers but I'm a bit lost now.

const str = '1 2 3 4';
let words = parseInt(str);
words = str.split(' ');

which results in

Array ["1", "2", "3", "4"]

However, I would like the result to be

[1, 2, 3, 4]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can apply a little map function to do that. When you're doing a simple conversion like this, you can use a single method in the map argument as a shortcut

str.split(' ').map(Number)

is the same as

str.split(' ').map(n => Number(n))

which is the same as

str.split(' ').map(n => {
  return Number(n);
})

const str = '1 2 3 4';
let words = str.split(' ').map(Number)
console.log(words);

about 4 years ago · Juan Pablo Isaza Relatório

0

str.split(' ').map(Number) is not a wrong answer for the given data but what if you are given a string like '1 2 3 4'? The result would be [1, 0, 0, 0, 2, 3, 0, 0, 0, 4].

So perhaps

[...str].reduce((r,c) => c === " " ? r : (r.push(+c),r),[]);

or

[...str].reduce((r,c) => c === " " ? r : r.concat(+c),[]);

might just do better.

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