Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

A function to reverse array

Hello,

I am trying to make my own reverse array function, I have the code below:

function reverseArrayInPlace(array) {
    for (var i = 0; i < array.length; i++) {
        array.unshift(array.pop());
    }
    return array;
}

var array = [1, 2, 3, 4, 5];
reverseArrayInPlace(array);

But it doesn't work. I don't understand. When I tried it one by one, it works.

Please help

1 Answer

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi FNU Christian

Your solution doesn't work because you keep putting the last item to the front of the array. So the first time in the loop the last item is added to the front; the second time the new last item is added to the front. In other words, you won't end up with the last item first.

Here's one solution that uses a temporary array and counts DOWNWARD each time in the loop letting you access the original array elements in reverse order.

function reverseArrayInPlace(array) {
  var tempArray = [];
    for (var i = array.length - 1; i >= 0; i--) {
        tempArray.push(array[i]);
    }
    return tempArray;
}

var array = [1, 2, 3, 4, 5];
console.log(reverseArrayInPlace(array));

Ahh, I see where my reasoning failed me!

Thank you