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
// Write your code here:
const sentence = ['sense.','make','all','will',
'This'];

const newSentence =[];
const reverseArray = (arr)=>{
  
  for(let i=0; i< arr.length;i++){
    newSentence.unshift(arr[i]);
  };
  return newSentence;
}
console.log(reverseArray(sentence))

This code works perfectly (and matches alternate solution given), yet it will not pass code checker. A bug???

Never mind. I figured it out. New array should be declared inside function. :thinking:

I couldn’t for my life get it to work with the new variable inside of the function (something I figured out afterwards though) so here’s my solution:

const array1 = ['one', 'two', 'three'];
const array2 = [];


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

reverseArray(array1, array2);
console.log(array2); // Prints: three two one

It did, however, not get me a green checkmark so had to replace with solution code to pass. But my code does the job. One benefit I can see with it is that it can push the reversed array into an already existing array, if you would ever need that hehe.

Just wanted to post my solution.

const reverseArray = arrayArg => {

  let newArray = [];

  let count = arrayArg.length;

  for(let i = 0; i < count; i++){    

    newArray.push(arrayArg.pop());

    //DEBUG CODE - console shows the process

    console.log(`old array: `, arrayArg);

    console.log(`new array: `, newArray);

    //DEBUG CODE    

  }

  return newArray;

};