SepZ
SepZ

Reputation: 11

Confused on reversing an array

I want to reverse an array that I input into a function.

But for some reason the console returns the first value of the array instead of taking the full array within the while loop so it can unshift the value at the end to the front then delete that same value.

function littleWHEW(lemonade) {
  let i = lemonade.length - 1;
  while (i >= 0) {     
    lemonade.unshift(lemonade[i])
    lemonade.pop(lemonade[i])
    i = i - 1
  }
  return lemonade
}

console.info(littleWHEW([1,2,3,4,5]))

Upvotes: 0

Views: 83

Answers (2)

Stev Ngo
Stev Ngo

Reputation: 94

Since you asked for explanation, let's take a deep investigation. Before we do, please take a look at unshift and pop

Firstly i = 4. Here're what happens in one loop:

  1. [1,2,3,4,5] is the original array. lemonade.unshift(lemonade[i]) adds one element to the first position of lemonade. At this point i = 4 so lemonade[4] = 5, we have [5,1,2,3,4,5] (notice the bold).
  2. Now you pop the last one out. [5,1,2,3,4,5] becomes [5,1,2,3,4].
  3. You decrease i.

Now i = 3, And here're what happens in second loop:

  1. [5,1,2,3,4] is the original array. lemonade.unshift(lemonade[i]) adds one element to the first position of lemonade. At this point i = 3 so lemonade[3] = 3, we have [3,5,1,2,3,4] (notice the bold).
  2. Now you pop the last one out. [3,5,1,2,3,4] becomes [3,5,1,2,3].
  3. You decrease i.

After one loop, your i does not point to the last element as expected, and makes things wrong (as second loop does).

Upvotes: 0

aryanm
aryanm

Reputation: 1259

Just use the

reverse()

method:

function littleWHEW(lemonade) {
   return lemonade.reverse();
}

You should not add a parameter to the pop() method, by the way.

Upvotes: 1

Related Questions