Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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 Respuestas
Responde la pregunta

0

Try this

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

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda