FAQ: Code Challenges: Intermediate JavaScript - reverseArray()

Hi everyone,

I’m looking for some help with this challenge.
I could tackle this out with a simple for loop.
But I was trying a more elegant solution and realized this code doesn’t pass the tests

const reverseArray = array => array.reduceRight((accu, elem) => accu.concat(elem), []) ;

Any idea why ?
Thanks !

Your solution is more advanced than the lesson checker expects. It is looking for an iterative approach using for loop.

Concat will give you a problem when you reverse an array of arrays and try to join them with concat: [[1], [2, 3], [4]]. The test file has a test for this and gives a hint in the error msg. You can replace concat-call with the JS spread-operator to create the new longer array as you are accumulating:

[...accu, elem]
2 Likes

Oh, I did not consider testing with nested arrays.
And did not know about the spread operator, your post is really helpful ! Thank you !

1 Like

The “View Solution” function is faulty, because it does not keep the code but rather overwrite my own code. This should be corrected.

It was Cool, but why unable to use any other argument name to the function only 'obj ’ is working

It shouldn’t matter what name we use for the parameter. It’s just a variable.

Forgive my inexperience but I do believe from what I am reading that your function is taking in the wrong array. You have your function that takes in newArr when it should in fact be taking the initial (sentence) variable and then pushing to newArr. hope this helps.

Can someone help me understand why this doesn’t work? It only prints the last index first and then nothing else

function reverseArray (arr) {
    for (let i = arr.length-1; i>=0; i--) {

        return arr[i];

      }
}

const sentence = ['sense.','make', 'all', 'will', 'This'];

console.log(reverseArray(sentence));

When you return, you are exiting the function with a return-value. So the first time your for-loop encounters:

return arr[i];

It exist the function and returns arr[i], which is the last word in your array. So this for-loop is not looping. You can instead build up a new array in the loop and return that as one strategy.

2 Likes

Thank you! Appreciate the explanation :slight_smile:

Thanks, that makes a lot more sense!

Careful how quickly you draw any conclusions. There are at least two things wrong in that example.

  • sentence.length
  • console.log(word[i])

sentence may be the argument, but it is not the parameter, word is.

for (let i = word.length - 1; ...)

Not sure one likes the choice of name for the array… sentence. It is not a sentence, but an array. If we reverse it, it will still be an array (unless we join() it).

Logging is the not the same or even a substitute for return. The function should be returning an array.

Arrays have elements, not words (although the above is true for both terms).

const reverseArray= array => {
  result = [];
  for (let index = array.length - 1; index >= 0; index--) {
    result.push(array[index]);
  }
  return result;
}

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

Sorry, I am not trying t jump to any conclusions, but his example is the only one that passed for me. I tried other ones and they didn’t work. It is frustrating, because I learned and did all the lessons without skipping and I still cannot identify solutions easy for these challenges. :’(

Could you please tell me how could we have done this differently? For some reason, I can write these things separately, but figuring out how to use variables, functions, built-in methods and all that other stuff TOGETHER is my problem. How do you know when to use what?

Also, in this example, I thought that we didn’t have to use built-in methods as they encouraged us to find solutions without relying on them. Is there something I am missing?

Sorry for being annoying and thank you for your time!

You will eventually know better once you have more hands on experience working with them. This takes time and practice.

We know what variables are… essentially address pointers; they don’t do anything (behavior) but only reference a value or object. When variables are given new values they change the pointer to where the new value resides in memory. That’s what makes them dynamic in nature, save for const.

Functions are reusable blocks of code that can be repeatedly called on new values with the return based upon the values handed in. The code inside a function is inline code but with its own namespace (scope).

We can write inline code that will perform once and then be done, or we can write that same code in a function and make it recallable.

Eg.

for (let i = 0; i < 10; i++) {
  console.log(i + 1);
}

Output

1 2 3 4 5 6 7 8 9 10 (on separate lines)

The above loop will run one time only since JS cannot go back up the script to run code a second time. That’s where a function comes in.

const sequence = function (start, end) {
  for (let i = 0; i < 10; i++) {
    console.log(i + 1);
  }
}

Now we can run the code over and over with different (or same) inputs.

sequence(10, 20)

Output

11 12 13 14 15 16 17 18 19 20

As we learn and practice using built in functions we increase the number of options we have in choosing how to construct our algorithms. Only reading, understanding and practicing will help to cement these new options.

1 Like

Wow, your explanation was so clear it made me really understand the logic better! Even the fact that you gave me an example where you used variables, functions, loops, parameters and arguments shows how strong of a programmer you are! Thank you so much! :100:

1 Like

Hi there,
I’m relatively new here, could anyone explain me this block of code step by step?
Any help would be amazing, thank you.

const reverseArray = array => {

const reversed = ;

for (let i = array.length - 1; i >= 0; i–) {

reversed.push(array[i]);

}

return reversed;

};

const sentence = [‘sense.’,‘make’, ‘all’, ‘will’, ‘This’];

console.log(reverseArray(sentence))

I have a doubt. Why .push is necessary?

‘Necessary’ is difficult to answer. Does it add to the flexibility of working with arrays? Yes. There are logic constructs where .push() and .pop() are used together to emulate stack behavior (last on, first off).

There are other ways to extend an array, but one would venture that .push() is the easiest one to work with. A big factor in its favor is its predictability. It always works the same way and the results are always as expected.

1 Like

I have a question, this is my code:

const reverseArray = function(array){

let rev = new Array;

console.log(array.length)

console.log(array)

for(var i = array.length - 1; i >=0; i--){

  console.log(array[i])

  rev.push(array[i]);

}

return rev;

}

Why my starting point is array.length - 1?