Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reverse array in javascript from eloquent book

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading