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

120
Visualizações
Search String Custom function algorithm

I want to condition the string that I Inputted value ("ello") and variable("hello").

If It found in string("hello"), the return value should be "ello". If not found, the return value should be -1.

But it returned "llll" 4 times because of condition (strs[i] == arrayS[tempVal]).

How can I get the correct answer as mentioned above?

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i++) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
      }
    }
    tempVal++;
  }

  return tempStr;
}

const res = searchStr("ello");
console.log('res', res)

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

0

According to you, logic is correct just break the for a loop when the condition is fulfilled. Check below snippet and console output.

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i++) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
        break;
      }
    }
    tempVal++;
  }
  return tempStr;
}

const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);

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