1

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?

1
  • No there is absolutely no way that you can do this with a .forEach() loop. Commented Apr 23, 2018 at 19:23

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

That's actually a pretty smart way of doing this! Thanks!
note the users output produces undefined, 10, 9, 8 not sure if that is intentional or not
0

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

1 Comment

Code dumps are not useful answers. Say what you did, and more importantly why. But note that you're visiting the entries in the wrong order.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.