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.