1

I need create a function that prints an array in reverse. The array is:

var array = [1,2,3,4,5]

My attempt is:

function printReverse(){
        for (i = array.length ; i >= 0;i--){
                console.log(array[i]);
        }
}

So i wonder if you can create the same think with foreach. I could not find anything in the web about it

2

1 Answer 1

1

forEach will strictly 'enumerate' forward through the array, but the callback to forEach will be passed three arguments: the current item, the index of that item, and a reference to the original array. You can use the index to walk backwards from the end. For example:

var array = [1, 2, 3, 4, 5];
array.forEach((_, i, a) => console.log(a[a.length - i - 1]));

Another trick is to use reduceRight to enumerate the items in reverse. The callback here will be passed an accumulator as the first argument (which you can simply ignore) and the item as the second argument. You'll have to pass in a value to initialize the accumulator as well, but again it doesn't really matter what that value is since you'll be ignoring it in this case:

var array = [1, 2, 3, 4, 5];
array.reduceRight((_, x) => console.log(x), 0);

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

2 Comments

what "a" goes for in foreach i cant understend
@AlphaPigVLOG That's a reference to the original array. It would be equivalent to array.forEach((_, i) => console.log(array[array.length - i - 1]));.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.