Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip first iteration during forEach loop

How can I skip the first iteration in a forEach loop? I've got my forEach loop working as expected but I need to start on the second item totally ignoring the first item. I'm using ES6.

cars.forEach(car => {...do something});

I thought I could maybe do something like

cars.skip(1).forEach(car => {...do something});
like image 794
luke jon Avatar asked Feb 24 '26 21:02

luke jon


2 Answers

you need to check index, and use return on that value, what you need. In your case you need to skip zero index (0), here is code

const cars = ['audi', 'bmw', 'maybach']

cars.forEach((car, index) => {
  if (index === 0) return;
  console.log(car)
});

this code will show 'bmw' and 'maybach'

like image 91
Paul Zaslavskij Avatar answered Feb 27 '26 11:02

Paul Zaslavskij


Writing out my comment as an answer:

cars.slice(1).forEach(car => { do something });

MDN reference to slice method: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

like image 40
Johan Maes Avatar answered Feb 27 '26 10:02

Johan Maes