0

This code, modifies an array(argument) and returns that same array. Please explain unambiguously how the function does this.

function reverseArray(array){ for(let x=0;x<Math.floor(array.length/2);x++){ let old=array[x]; array[x]=array[array.length-1-x]; array[array.length-1-x]=old; } return array; }

14th Aug 2018, 9:12 AM
Odus Obafemi
Odus Obafemi - avatar
4 Answers
+ 2
The code translates to : for a variable x which is initially 0, which is to be incremented by one every time to half the array size (The floor function helps convert the decimal values to the nearest integer which may be smaller or equal) : Let a new variable 'old' be equal to the array's value at index 'x'. Then make the array's value at index 'x' equal to the array's value at index 'length-1-x' Finally make the array's value at 'length-1-x' equal to the old value which was saved earlier. /* Now, for an array 2,3,4,5, if x is 0 and 1, the elements in consideration are 2 and 3, and the complement elements (The elements at 4(length)-1-x, or 3 and 2 in this case) are 5 and 4. Basically, we want to swap these so that we can modify the array to 5 4 3 2. */
14th Aug 2018, 10:02 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
okay, thanks. you did good... but please @ array.length which of the lengths does the function uses, the new array, or the old array’s length, and does the length of the old array reduces, or the length of the new array increases to be substituted for the array.length, making the loop to go on and on... please explain further how does this length thing works..(that makes the loop not to terminate) because it’s half of the length that’s being considered here...
14th Aug 2018, 3:05 PM
Odus Obafemi
Odus Obafemi - avatar
+ 1
Odus Obafemi The length remains the same, as all we have to do is reverse the same array. The loop thus runs for a finite amount of time. We consider half the length, as after we reach the first half, the array is completely reversed.
14th Aug 2018, 3:11 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Kinshuk Vasisht I’ll be sincere with you, I still don’t really get it this way, Please If you can.. explain it, one line after the other, how the loop works. especially with the three lines after it.. please. i so much appreciate your time..
14th Aug 2018, 6:25 PM
Odus Obafemi
Odus Obafemi - avatar