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});
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});
Share
Improve this question
asked Aug 14, 2020 at 5:26
luke jonluke jon
2011 gold badge2 silver badges10 bronze badges
3
|
6 Answers
Reset to default 11you 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'
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
Should be a fairly simple one-item test - your 'do something' function can set/read an external variable as required.
let myArray = [1,2,3,4,5];
let firstItem = true;
myArray.forEach(item => {
if (firstItem != true){
console.log(item);
} else {
firstItem = false;
}
});
since there is counting variable available in forEach loop, you manually make one to count it.
let count = 0;
let skipVal = 0;
cars.forEach(car => {
count++;
if (count != skipVal){
...do something
}
});
How about a sliced for loop?
const s=['car','bike','plane']
for(each of s.slice(1))console.log(each)
As of ECMAScript 2025, you can call drop
on an iterable, so you can now do:
const cars = ["Honda", "Mercedez", "Tesla", "Peugeot"];
cars.values().drop(1).forEach(car => console.log(car));
for
loop and start the index at1
instead of0
..forEach()
is so yesterday. – jfriend00 Commented Aug 14, 2020 at 8:42