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

193
Visualizações
Finding both characters and putting them in a new array

I've created a function that passes in a string and a character. The string is saturday and the character is a.

I want the result to be an array that contains all the index numbers of where the letter 'a' sits in saturday.

Then array ends up with only [1]. So it finds the first a sitting at the second index. I tested this by changing saturday to soturday and the console prints the array with [6].

I want the result to be [1, 6]

I've tried putting the return result outside the next set of {} braces but no joy.

const subLength = (str, cha) => {
  let result = [];

  for (let i = 0; i < str.length; i++) {

    if (str.charAt(i) === cha) {
      result.push(str.indexOf(cha));

      return result;
    }
  }

};
console.log(subLength('Saturday', 'a'));

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

0

2 small problems with your code

  1. The return statement is in the for loop. The first time the loop hits that your loop will stop and the function will return. This is why you are only getting 1 result. Move the return outside the loop.

  2. Once the above is fixed you will realize that your array will now return [1, 1]. This is because str.indexOf(cha) will always return 1 since it's returning the index of the first a. To fix this, you should be appending the index i to your array instead since it represents the index of the current char.

const subLength = (str, cha) => {
  let result = [];

  for (let i = 0; i < str.length; i++) {

    if (str.charAt(i) === cha) {
      result.push(i);
    }
  }

  return result;
};
console.log(subLength('Saturday', 'a'));

about 4 years ago · Juan Pablo Isaza Relatório

0

How about putting the return result; outside of the for loop?

about 4 years ago · Juan Pablo Isaza Relatório

0

Something like this should work, if it is case-sensitive

const subLength = (str, cha) => {
    const chaArr = str.split('');
    const result = [];
    chaArr.forEach((v, i) => {
        if (v === cha) result.push(i);
    })
    return result

};
console.log(subLength('Saturday', 'a'));
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