2

So I want to go through an list of objects but I cant index it but can use forEach to go through the elements... My problem is I need to go from the last Object to the first but dont know how to do that with the forEach function! If i'd do a for loop it would look something like this:

var test = [1,2,3,4,5]
   for (let i = test.length; i > -1; i=i-1) {
       console.log(test[i])
   }

But as I explained I somehow cant index it. So can you help me?

4 Answers 4

2

You can reverse() the array before the loop:

var test = [1,2,3,4,5]
 
test.reverse().forEach(e => console.log(e));

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

Comments

1

Here is the code for your problem:

var test = [1, 2, 3, 4, 5]
    for (let i = test.length - 1; i >= 0; i--) {
      console.log(test[i])
    } 

Comments

1

This is a variant of Severin.Hersche's approach:

const test = [1, 2, 3, 4, 5];
for (let i = test.length;i--;) console.log(test[i]);

Comments

0

Please use this code.

var test = [1,2,3,4,5]
test.forEach((val, index) => console.log(test[test.length - index - 1]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.