FAQ: Code Challenges: Intermediate JavaScript - reverseArray()

This community-built FAQ covers the “reverseArray()” exercise from the lesson “Code Challenges: Intermediate JavaScript”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

FAQs on the exercise reverseArray()

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Can anyone tell me why this code is not considered to be a viable solution to this challenge?

let array = [];
function reverseArray(list) {
  list.forEach(stack);
  return array;
}
function stack(item) {
  array.unshift(item);
}

It produces the desired effect.

1 Like

Yes, it does produce the desired effect, although the global object is created only once and never cleared of its contents so any subsequent test will return a larger array than expected.

function reverseArray(list) {
  array = [];
  list.forEach(stack);
  return array;
}
function stack(item) {
  array.unshift(item);
}
let array;

Console…

 > list = [1,2,3,4,5,6,7,8,9]
<- (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
 > reverseArray(list)
<- (9) [9, 8, 7, 6, 5, 4, 3, 2, 1]
 > list = [10,20,30,40,50,60,70,80,90]
<- (9) [10, 20, 30, 40, 50, 60, 70, 80, 90]
 > reverseArray(list)
<- (9) [90, 80, 70, 60, 50, 40, 30, 20, 10]

Now we have to ask what value does stack have to a larger program? None, if it does not involve the array object. Having a function with a dependency on a global object is a scary path.

So encapsulate the function where it is needed.

function reverseArray(list) {
  function stack(item) {
    array.unshift(item);
  }
  let array = [];
  list.forEach(stack);
  return array;
}

Now the function is completely free of dependencies and can return a true array relative to the parameter.

8 Likes

That makes sense. Thank you!

1 Like

Would this work as a solution? I keep getting the following error

Your function should return an array with the elements of the argument array in reversed order. It should work on arrays of numbers.

const reverseArray= (word=>{
  for (let i=sentence.length-1; i>=0; i--)
  console.log(word[i])
})

const sentence = ['sense.','make', 'all', 'will', 'This'];
reverseArray(sentence)
1 Like
const reverseArray= (word=>{
  for (let i=sentence.length-1; i>=0; i--)
  console.log(word[i])
})

The syntax looks a little bit off.

const reverseArray = obj => {
  for (let i = obj.length-1; i>=0; i--) {
    console.log(obj[i])
  }
}

The main issue is that the function does not return an array as expected.

const reverseArray = obj => {
  reversed = [];
  for (let i = obj.length-1; i>=0; i--) {
    reversed.push(obj[i]);
  }
  return reversed;
}
3 Likes

It returns the original array in reverse order but what was requested was a new array which I didn’t create. Understood, thanks for the input.

2 Likes

I trust that last example does return a new array, and does not affect the original in any way?

array = [3, 6, 9, 12, 15]

newArray = reverseArray(array)

console.log(array)        // [3, 6, 9, 12, 15]
console.log(newArray)     // [15, 12, 9, 6, 3]

const aliens = [“Blorgous”, “Glamyx”, “Wegord”, “SpaceKing”];

function greetAliens(list) {
for (let i = 0 ; i < list.length ; i++){
return console.log(Oh powerful ${list[i]}, we humans offer our unconditional surrender!);
}
}

greetAliens(aliens);

why my output is only one string ?


Oh powerful Blorgous, we humans offer our unconditional surrender!


Which part of my “for” loop I am missing out ?

Hello there, I’m trying to get the expected result writing my own “reverse” function, but something goes wrong after the first two iterations, the output should be reverse, instead it is 4,3,3,4

const sentence = [
  "1", "2","3","4"]

const reverseArray = (x) => {
  let placeholder = x
  for (let i = x.length-1; i >= 0; i--) {
    placeholder[(x.length-1)-i] = x[i]
  }
  return placeholder
}
console.log(reverseArray(sentence))```

Output: 4, 3, 3, 4

Because an array is referencing multiple values it cannot be copied by reference, only. placeholder is in fact just another reference to x, not an independent copy.

placeholder = x.slice()

will produce a shallow copy that is not bound to x.

If what you want it an indexable array that is the same length as x, but with undefined elements,

placeholder = new Array(x.length)

My decision was exactly the same with solution code, produced desired effect but system still wont pass my answer untill i clicked “solution”. More lessons i pass—more errors and bugs in codecademy system. First lessons explained really good, but now theres is a feeling that you guys stopped making it right.

2 Likes

Hey @css5486552930, welcome to the forums!

I can completely understand the problem you’re having. Unfortunately, Codecademy isn’t perfect and since it’s created by people, there will be bugs. The most helpful thing you can do as a user is report the bugs in the bug reporting lesson in the exercise, and then posting a topic in the #community:Codecademy-Bug-Reporting section of the forums with a link to the exercise so we can check out the problem ourselves.

I came across a great article which helped me with this exercise. https://medium.com/@josephcardillo/how-to-reverse-arrays-in-javascript-without-using-reverse-ae995904efbe

also in the responses at the bottom, there’s reply which shows how you can complete this exercise using the .splice method.

A great read. Hope this helps some folks out.

6 Likes

Many or most of us do not have access to the comments. Can you tell us whether the .splice method is in-place or not?

    var myArray = [1, 3, 6, 9, 5, 2, 8, 5];
    var reverseArrayInPlaceFn = function (array) {
     var arrLength = array.length;
     for (i = 0; i < arrLength; i++) {
     myArray.splice(i, 0, myArray.pop());
     }
    }

We can see the immediate weakness…

myArray.splice(i, 0, myArray.pop())

Which array is the function supposed to be acting upon? array, or, myArray?

In-place would suggest an instance method similar to .sort(). We may need to create a class of our own rather than messing with the core objects.

class List extends Array {

}

Our List instances are all arrays, and inherit all the Array.prototype attributes and methods. We only need to append our custom method for List instances to inherit.

myArray = new List([1, 3, 6, 9, 5, 2, 8, 5]);
 > myArray instanceof List
<- true
 > Array.isArray(myArray)
<- true
 > 

I modified the code referred to by @jeremycorate in the comment to the article he referenced like so:

const myArray = [1, 'too', 3, 'for', 5, '6', 7, 'ate', 9, '10'];

const revArrayInPlace = arr => {
  for(let i = 0; i < arr.length; i++) {
    arr.splice(i, 0, arr.pop()); 
  }
}

console.log(myArray)
revArrayInPlace(myArray)
console.log(myArray)

Output:

[ 1, ‘too’, 3, ‘for’, 5, ‘6’, 7, ‘ate’, 9, ‘10’ ]
[ ‘10’, 9, ‘ate’, 7, ‘6’, 5, ‘for’, 3, ‘too’, 1 ]

Using splice() does work as an in-place solution.

1 Like

A bit of silliness, perhaps?

 > class List extends Array {
     constructor (list) {
       super();
       this.list = list;
     }
     reverse () {
       for(let i = 0; i < this.length; i++) {
         this.splice(i, 0, this.pop()); 
       }
     }
   }
<- undefined
 > myArray = new List([1, 3, 6, 9, 5, 2, 8, 5])
<- List [list: Array(8)]
 > myArray.list
<- (8) [1, 3, 6, 9, 5, 2, 8, 5]
 > myArray.list.reverse()
<- (8) [5, 8, 2, 5, 9, 6, 3, 1]
 > myArray.list
<- (8) [5, 8, 2, 5, 9, 6, 3, 1]
 > 
1 Like

So here is my solution. I seems to do the trick. I tried it with an array of numbers and another sentence and both turn out as expected.

Comments are welcome.