Currently, I'm working on a code challenge to reverse an array in place without using the reverse function while learning Javascript from Eloquent JavaScript.
function reverseArrayInPlace(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[(arr.length - 1) - i];
}
return arr;
}
After writing the above code, I encountered an issue where the reversal didn't work as intended due to reassigning values. For example, when I tried
reverseArrayInPlace([1, 2, 3, 4 ,5])
, it returned [5, 4, 3, 4, 5]
.
Here's the suggested 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;
}
I would appreciate it if someone could explain the solution and how it works so that I can gain a better understanding. Thank you :)