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

185
Visualizações
How to stop a loop after finding n elements javascript

I am writing a quick bit of code which find the first three even numbers in a random length of random numbers in an array.

  const getEven = (array) => {
  const evenArr = [];
  for (let index = 0; index < array.length; index++) {
    if (index % 2 != 0) {
      evenArr.push(array[index]);
    }
  }
  console.log(evenArr);
};

getEven([1, 2, 3, 4, 5, 6, 7, 8, 9]);
Output = [ 2, 4, 6, 8 ]

The question I have is, once it finds the first three even elements the loop continues to run, how can I stop it after finding the first three elements and is there a more efficient way of doing this?

I could use a filter but decided to go traditional and wrote a for-loop.

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

0

Try this

 if (index % 2 != 0 && evenArr.length<3) 
about 4 years ago · Juan Pablo Isaza Relatório

0

Well, you may just add break statement with your desired condition:

 const getEven = (array) => {
  const evenArr = [];
  for (let index = 0; index < array.length; index++) {
    if (index % 2 !== 0) {
      evenArr.push(array[index]);
    }
    
    if (evenArr.length === 3) {
      break;
    }
  }
  console.log(evenArr);
};

getEven([1, 2, 3, 4, 5, 6, 7, 8, 9]);
Output = [ 2, 4, 6, 8 ]
about 4 years ago · Juan Pablo Isaza Relatório

0

With your current approach, the easiest change would be to add break -statement to your loop:

  for (let index = 0; index < array.length; index++) {
    if (index % 2 != 0) {
      evenArr.push(array[index]);
      if (arrray.length >= 3) {
        break; // <= this will end the loop
      }
    }    
  }

It is also good to mention that your algorithm is collecting odd numbers not even numbers currently. SHould be index % 2 === 0.

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