javascriptnode.jsecmascript-6foreach

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

Solution

  • 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'