Actually I know there are easier ways to reverse arrays in js, But I need someone’s help to understand this reverse method.
Thank you for your help.
function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
console.log(array[array.length - 1 - i])
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
console.log(reverseArrayInPlace([1, 2, 3, 4])); // 4, 3, 2, 1
>Solution :
The code has two pointers: one at the start of the array (call this i), and one at the end of the array (call this n - 1 - i). For each iteration, we swap the values at both pointers. We repeat this until we get to i = floor(n / 2).
By swapping these indices, the array will eventually be reversed. It’s easier to see with an example. Suppose you have the array [1, 2, 3, 4, 5, 6].
Iteration 1: (i=0, n-1-i=5)
Pointers at 1 and 6. After swapping, Array=[6, 2, 3, 4, 5, 1]
Iteration 2: (i=1, n-1-i=4)
Pointers at 2 and 5. After swapping, Array=[6, 5, 3, 4, 2, 1]
Iteration 3: (i=2, n-1-i=3)
Pointers at 3 and 4. After swapping, Array=[6, 5, 4, 3, 2, 1]