Hi again @Christophe_H,
Here’s my feedback on your solutions for the exercise Reversing an Array.
Part 1 — Creating a new array which is the reverse of the original
Your following line of code…
newArr[i] = arr.length-i;
…will always produce an array of numbers which descend by decrements of -1 from the total number of elements to 1 e.g.
let originalArray = [1, 2, 3, 4, 5];
// => [5, 4, 3, 2, 1]
let originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
And so, as long as we always input arrays that start with 1 and rise by increments of +1 (whatever their length), this code appears to work. However, as soon as we try to reverse arrays such as the following, your code no longer produces the correct result:
let originalArray = [5, 7, 9, 11];
// => [4, 3, 2, 1]
let originalArray = ['A', 'B', 'C', 'D'];
// => [4, 3, 2, 1 ]
In order to get your code to always produce an array that’s the reverse of the input array, you need to change this line of code to something like the following:
newArr[i] = arr[arr.length-1-i];
Part 2 — Reversing the original array in place
Here you’re doing exactly the same as your Part 1 solution, the only difference being that it’s replacing the original array rather than creating a new one.
However, here, you cannot just make the same amendment as in Part 1, because that would produce the following:
//
let inputArray = [1, 2, 3, 4, 5];
// => [5, 4, 3, 4, 5]
let inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// => [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]
let inputArray = [5, 7, 9, 11];
// => [11, 9, 9, 11]
let inputArray = ['A', 'B', 'C', 'D'];
// => ['D', 'C', 'C', 'D' ]
Have you already looked at the model solution, and worked out how it achieves the desired result? If not, then, first of all, have a look at the hints (which you can display in the online course book by clicking below the exercise instructions). If you still don’t get it, have a look at other students’ posts here in this topic, with their attempts, solutions, and the help, comments and feedback posted as replies.
Once you’ve finally looked at the model answer and really understood it, another good learning approach to use is to then try the exercise again from scratch without looking back at the answer (like a memory test). You can also try to do this after having left it for a certain period of time (say, the next day, then after a few days, then a week etc. etc.) This builds up longer-term retention.
Let us know if you have any questions or need any further guidance.
Keep on learning! 