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

270
Visualizações
How to get only Numbers from a string and store it in an Array using Javascript

I have a string that contains a mix of characters and numbers. I want to separate out the numbers from the string and store them in an Array. So far I have been able to separate the strings and numbers and put them in Array and then able to get only numbers but the string type data is NaN. I am unable to get rid of NaN values from the Array.

So far my code looks like this:

arrayList = "abcd_456_yasdb_382_h_83_2";
new_arrayList = arrayList.split('_');
console.log(new_arrayList); // Output : [ 'abcd', '456', 'yasdb', '382', 'h', '83', '2' ]


new_arrayList = new_arrayList.map(Number);
console.log(new_arrayList); // Output :  [ NaN, 456, NaN, 382, NaN, 83, 2 ]

onlyNumArray = []

for(i =0; i<new_arrayList.length; i++) {
    // console.log(new_arrayList[i]);
    if(typeof (new_arrayList[i]) === "number" && typeof(new_arrayList[i]) != NaN) {
        onlyNumArray.push(new_arrayList[i])
    }
    else {
        console.log("Not a number")
    }
}
console.log(onlyNumArray)  // Output : [ NaN, 456, NaN, 382, NaN, 83, 2 ]

Output = [ NaN, 456, NaN, 382, NaN, 83, 2 ]
Expected Output = [456, 382,83,2]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Is there a reason you can't use Array#filter? Also, you can't check for NaN by equality (except that NaN != NaN as Passerby points out). You have to use isNaN (or Number#isNaN).

const input = 'abcd_456_yasdb_382_h_83_2';

const tokens = input
  .split('_')
  .map(Number)
  .filter(i => !isNaN(i));

console.log(tokens);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use the array.filter() method and do something like this :

const unfilteredArray = [ NaN, 456, NaN, 382, NaN, 83, 2 ]
const numbersArray = unfilteredArray.filter(Number)
// Output : [ 456, 382, 83, 2 ]
about 4 years ago · Juan Pablo Isaza Relatório

0

const newArrayList = arrayList.split('_').filter(element => {
  return Number.parseInt(element);
}).map(element => {
  return Number.parseInt(element)
});
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