I am trying to write code that reverses an array in place without using the reverse function (I'm busy learning JS so just doing an exercise from Eloquent JavaScript).
function reverseArrayInPlace(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[(arr.length - 1) - i];
}
return arr;
}
This was the code that I wrote which doesn't quite work, I know this is because I have already reassigned arr[0] and arr[1] so if I call reverseArrayInPlace([1, 2, 3, 4 ,5]), [5, 4, 3, 4, 5] is returned.
This was given as the solution:
function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
Could anyone please explain what's happening in the solution so I can better understand? Thanks :)
[ 1, 2, 3, 4, 5 ]being fed into your example. After the very first iteration, your code will be working with[ 5, 2, 3, 4, 5 ]. The1has disappeared entirely, and you'll never be able to retrieve it to set it as the last array item, where it ought to go. The given solution swaps two numbers at a time (starting with the first and last number). After a first iteration it will produce[ 5, 2, 3, 4, 1 ]. This solves the issue of disappearing data that your solution had.