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

Reversing an Array in JavaScript.

Hello Fellow Students!

I am trying to figure out an algorithm problem to where I would have to reverse the order of an Array.

For example if I had the array:

[-3,5,1,3,2,10]

I want to make a function that creates this array:

[10,2,3,1,5,-3]

I'm pretty much stuck on this algorithm. Here is what I have so far, but it doesn't provide the correct answer:

var x = [-3,5,1,3,2,10];


function reverse(a) {

  var counter = a.length - 1;

  for (var i = 0; i < a.length; i++) {

    var temp = a[i];
    a[i] = a[counter];
    counter--;

  }

  return a;

}

console.log(reverse(x)); // returns [10, 2, 3, 3, 2, 10]

The only methods I am allowed to use or .push, .pop, and .length and I am not allowed to store a temporary array in a variable.

Thank you in advance!

Tony, please note here which challenge you're having trouble with. There are, in fact, several ways to solve this without using .reverse, if it's not usable in the challenge.

If you need any more help, Tony, I'm here to help. =]

Thank you so much for such for being so helpful! :D

No problem at all! I thought I had responded earlier to you about your comment, but I guess I didn't submit it. I had just said that I'm glad you understand everything and good luck in your course!

2 Answers

Hey Tony,

One way to do this without using pop or push (only length) is to modify your for loop to start from the given array's length minus 1 (which is equal to the last index of the array) and then iterate down to 0 (first index of array of course) and use a counter variable to store the values in a temporary array that are taken from the end of the received array:

var x = [-3,5,1,3,2,10];

function reverse (a) {
var b = [], counter = 0;
for (var i = a.length-1; i >= 0; i -= 1) {
b[counter] = a[i];
counter += 1;
}
return b;
}

console.log(reverse(x));

Awesome answer, this really helps. However do you know if there is a way to do this without having a temporary empty array? I forgot to mention this as my challenge also mentions this.

How are they expecting you to output information? Can each value of the array be outputted individually or must it appear in a collection? I mean, in order for the code to be outputted to a collection such as an array, it needs to be stored in a temporary container. That data has to have somewhere to go so that it can be re-ordered, whether it's output to the screen in some form or output to a container.

I found a way to do this with a while loop, however it's returning undefined for some reason.

var x = [-3,5,1,3,2,10];


function reverse(a) {

  var first = 0;
  var last = a.length - 1;

  while (first < last) {
    var b = a[first];
    a[first] = a[last];
    a[last] = b;

    first++;
    last++;
  }

}

console.log(reverse(x));

Any ideas?

If you said you can't use a variable to store the array values in, you're violating that rule by using the b variable, but then again, there's no other way to do it without a temporary container such as the b variable.

Functions will always return undefined when there is no defined return value. Also you need to have the last variable subtracting because otherwise the loop is infinite. First can never be less than last if they are both going into positive infinity.

One more thing is that using the loop this way permanently changes the array that is fed into the function. It doesn't just return a copy of the array reversed; it permanently reverses it. This is often not the behavior you want. You'd want to have a copy of the information to do with as you please while preserving the formatting of the original array. I know this is a challenge, but it doesn't seem like a very well made challenge to be honest.

var x = [-3,5,1,3,2,10];


function reverse(a) {

  var first = 0;
  var last = a.length - 1;

  while (first < last) {
    var b = a[first];
    a[first] = a[last];
    a[last] = b;

    first++;
    last--;
  }
return a;
}

console.log(reverse(x));
//shows that x is permanently changed
console.log("x is now: "+x);

Just to give more reason and credence as to why I say this challenge isn't right is to look at the default global JavaScript functions. Let's say "parseInt" for example. You know "parseInt" grabs a number from a string and returns that number. But it does not permanently change the variable that is called into it.

var width = "130px";
console.log(parseInt(width));
console.log(width);

You can notice after running this that width did not change after running parseInt() on it because it preserves the original formatting of the variable called.

Thank you so much for helping me with this challenge. The challenge didn't let me specifically use an empty "array" variable, however the variable that I used was fine according to the challenge that I had received. While I do agree with everything you say here that it is not good programming practice to do it in this way, the whole purpose of the challenge was just to reverse the array and not to create it to use for a long term program. I completely understand that it is bad practice to change an initial value of a variable.

Hey, this might help you a little understand how to accomplish it. When you pop and element from an array, it removes the last item and it also stores it, in other words, you can use the popped item to save it in a variable. The push method adds items to the end of the array. so you can pop each item one by one from the array and push them into a new array.

let me know if you have any questions :)