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 :)
So here is what is happening in this function:
for(let i = 0; i < Math.floor(array.length / 2); i++)
:
they are using the Math.floor()
method to make sure that you only iterate through half of the array. That is why your original solution repeated elements instead of reversing them.
let old = array[i]
:
This is a temporary variable to hold the element at the current index in the loop while you swap them.
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
this swaps the elements.
which only leaves return array;