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

129
Visualizações
Function take in array of string return only strings with that have number(s) in them. Or return empty array if none

The function has 1 parameter: an array. It should iterate through the array and return strings that contain a number in them. If none of them have an number it will return an empty array.

The code I have written so far seems too verbose. Sometimes it does not return the correct value. I am looking for any ways to shorten the code or improve it.

function numInStr(arr) {
    var stringsWithNum = [];
  for(var x = 0; x < arr.length - 1; x++) {
    for (var y = 0; y < arr[x].length - 1;y++) {
      //console.log(typeof arr[x][y]);
            if('0123456789'.indexOf(arr[x][y]) !== -1) {        
                stringsWithNum.push(arr[x]);
        break;              
      }
    }
  }
  return stringsWithNum;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can shorten your code considerably by using .filter() to filter out the elements containing numbers, and using .match() to test whether the elements contain a number.

This eliminates the need to create and maintain (and possibly incorrectly set) array indexes.

function numInStr(arr) {
    return arr.filter(function (elmt) {
        return elmt.match(/\d/)
    })
}

console.log(numInStr(['foo', 'ab12', '34asdf', 'bar']))
// Array [ "ab12", "34asdf" ]
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