Home > database >  How to stop a loop after finding n elements javascript
How to stop a loop after finding n elements javascript

Time:04-18

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.

CodePudding user response:

Try this

 if (index % 2 != 0 && evenArr.length<3) 

CodePudding user response:

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 ]

CodePudding user response:

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.

CodePudding user response:

Well you can use break

   if (evenArr.length === 3) {
      break;
   }

or return

   if (evenArr.length === 3) {
      return;
   }

or better:

   if (evenArr.length === 3) {
      return evenArr
   }

Return not just stops the loop but the whole function

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) return evenArr;
  }
  return evenArr
};
  • Related