Search code examples
javascriptarraysloops

JavaScript - reverse an array in a specific way


I'm doing an algorithm course and here is the instructor's answer about how to reverse an array without using reverse js method:

function solution(arr) {
  for(var i=0; i < arr.length/2; i++) {
    var tempVar = arr[i]
    arr[i] = arr[arr.length - 1 - i]
    arr[arr.length - 1 - i] = tempVar
  }

  return arr
}

I did understand everything, EXCEPT this detail:

arr.length/2

In this line below:

 for(var i=0; i < arr.length/2; i++) {

what does it mean? What its purpose?


Solution

  • To reverse a string, you have to swap characters of first half of the string with the last half.

    let str = 'abcde';
    

    You have to swap a with e, b with d.

    ab is the first half of the string. So simply run loop over the first half of the string and swap ith character with arr.length - 1 - ith character as below

    var tempVar = arr[i]
    arr[i] = arr[arr.length - 1 - i]
    arr[arr.length - 1 - i] = tempVar