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

gaetanoM
  • 41,594
  • 6
  • 42
  • 61
A.P
  • 23
  • 4

1 Answers1

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);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • what "a" goes for in foreach i cant understend – A.P Apr 24 '19 at 21:09
  • @AlphaPigVLOG That's a reference to the original array. It would be equivalent to `array.forEach((_, i) => console.log(array[array.length - i - 1]));`. – p.s.w.g Apr 24 '19 at 21:10