OrpheuZ
OrpheuZ

Reputation: 37

Looping over the last few entries of an array

I'm trying to have a forEach loop over an array, but only the last few entries.

I'd know how to do this in a for loop, that'd look a bit like this:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 

/* This will loop over the last 3 entries */
for(var x = arr.length; x >= 7; x--){
    console.log(arr[x]);
}

Would there be any way of achieving the same results in a forEach loop?

Upvotes: 1

Views: 60

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386550

You could take a classic approach by taking the count of the last elements and use it as counter and an offset for the index.

Then loop with while by decrementing and checking the counter.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    last = 3,
    offset = array.length - last;
    
while (last--) {
    console.log(array[last + offset]);
}

Upvotes: 0

Aaditya Thakkar
Aaditya Thakkar

Reputation: 1820

This is how you do it with forEach loop:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
arr.forEach((element, index) => {
  if(index>7) console.log(arr[index]);
})

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can use slice() and reverse() methods and then forEach() loop on that new array.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
arr.slice(-3).reverse().forEach(e => console.log(e))

Upvotes: 2

Related Questions