FAQ: Code Challenges: Intermediate JavaScript - reverseArray()

How does .unshift work in this format? Im only reading about unshift moving elements to the beginning of an array. Imagine its moving each element to the beginning one at a time as the loop rolls thru. Just didnt expect the usage of the method within a loop.

Array.unshift(value) will insert value at the front of the array.

1 Like

My code produces the desired results and works in all test cases, but the exercise is not accepting the answer.
What am I doing wrong here?

let revArr = [];
const reverseArray = (arr) => {
  for (let i = arr.length-1; i >= 0; i--) {
    revArr.push(arr[i])
    }
    return revArr;
  };

const sentence = ['sense.','make', 'all', 'will', 'This'];
console.log(reverseArray(sentence))

// Output: [ 'This', 'will', 'all', 'make', 'sense.' ]

Hey ! Can you tell me why my code works but its rejected by the platform ? Thanks!

I had the same question as @mike.webster1 .

I’m assuming a loop is required to use .unshift to reverse an array, correct?

It will require some form of iteration, yes.

array = "JavaScript".split('')
s = array.slice()              //  make a copy we can destroy
t = []                         //  results array
while (s.length) {
  t.unshift(s.shift())
}
console.log(t.join(''))
tpircSavaJ

That’s one approach. You will surely want to come up with one of your own making.

1 Like

I was wondering why the iterator variable below included -1 in let = arr.length - 1 .

why cant it be let=arr.length ?

function reverseArray(arr) {
    let reversed = [];
    for (let i = arr.length; i >= 0; i--) {
        reversed.push(arr[i]);
    }
    return reversed
}

So I erased the the - 1 and this was returned

[ undefined, 'This', 'will', 'all', 'make', 'sense.' ]

Why does it return undefined first?

Because there is no defined value at arr[arr.length].

I’m not seeing something here…

Isn’t it defined when we pass the let reversed array to it?

Thanks

arr = [1, 2, 3, 4, 5, 6]

arr.length is 6 but there is no defined value at arr[6].

I don’t see where we look for a defined value of arr[arr.length] in this excercise

Are we -1 on arr.length because the elements in const sentence are zero indexed?

['sense.','make', 'all', 'will', 'This'] ‘sense.’ = 0 ‘make’ = 1, ‘all’= 2 ‘will’ =3 ,‘this’ = 4

If we - 1 we take away the undefined

Am I close? lol

Thank you for your patience. You’re giving me simple answers and examples and I should be getting it. But I think I’m missing an understanding somewhere.

1 Like

That is correct. One less than the length gives us the last index.

1 Like

I can’t find out if there is a reason this code doesn’t work. It shows that it stops 2 words short.

const reverseArray = (arr) => {
    const arr2 = [];
for (let i = 0; i < arr.length; i++) {
  arr2.push(arr.pop());
};
return arr2;
};

Using a for loop can present with issues when the array length is changing. Since you are using .pop() there is a constant state change of the array, it’s getting shorter. Given this, we can use that as the condition to monitor.

We don’t want to destroy the array. It should remain intact and a new array returned. The way to preserve the original array is to take a snapshot and assign it to a new variable, then destroy that object.

arr1 = arr.slice()

The condition to watch for is arr1.length < 1.

while (arr1.length > 0) {
    arr2.push(arr1.pop())
}

Thanks this makes a lot of sense, so to use this I should set a separate variable to the array length or use a different method to avoid modifying the array.

1 Like

The separate variable, arr1 is a shallow copy of the arr, allowing us preserve the original (which lives in global scope and may still serve some purpose outside of this function).

Once we have a safe, volatile copy we are free to destroy it, which repeated pops will eventually do. The control on the while loop is the existence of the array elements. When there are no more elements the loop ends.

Yes, there are other methods at our disposal that will also preserve the original array. Above we effectively consumed our copy. Let’s consider another approach that does not mutate the original array, but that also does not need a copy. It will just read the array, and go from there to build the new array.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const arr2 = []
for (let x of arr) {
    arr2.unshift(x)
}
console.log(arr2)    //  [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
console.log(arr)     //  [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
1 Like