Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Cómo detener un bucle después de encontrar n elementos javascript

Estoy escribiendo un código rápido que encuentra los primeros tres números pares en una longitud aleatoria de números aleatorios en una matriz.

 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 ]

La pregunta que tengo es, una vez que encuentra los primeros tres elementos pares, el ciclo continúa ejecutándose, ¿cómo puedo detenerlo después de encontrar los primeros tres elementos? ¿Existe una forma más eficiente de hacerlo?

Podría usar un filtro, pero decidí volverme tradicional y escribí un ciclo for.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Prueba esto

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

0

Bueno, puede agregar una declaración de break con la condición deseada:

 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 Report

0

Con su enfoque actual, el cambio más fácil sería agregar una declaración de break a su bucle:

 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 } } }

También es bueno mencionar que su algoritmo está recolectando números impares, no números pares actualmente. Debería ser index % 2 === 0 .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!