I am trying to reverse an array using javascript recursion but its not working. Need help what I am missing here.
function reverseArrayHelper(left, right, arr) {
if (left >= right) return; // base condition: if l an r collide then only return
// do the small task: swapping left with right
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
// arr[left], arr[right] = arr[right], arr[left]
return reverseArrayHelper(left + 1, right - 1, arr); // ask recursion to do the remaining task
}
function reverseArray(arr, m) {
return reverseArrayHelper(m + 1, arr.length - 1, arr);
}
console.log(reverseArray([1, 2, 3, 4, 5, 6], 3));
3
Answers
If you are worried about the response is undefined, you have to return the array here
if (left >= right) return arr;
. Since you were not returning a value in this line, the response was undefined.But the logic for the reverse is up to you.
The issue with the code is that you are not returning the modified array from the
reverseArray
function.In the
reverseArrayHelper
function, I addedarr
as the base case return value. This ensures that the modified array is returned all the way up the recursive calls.With this code, to reverse the entire array you should:
you don’t need to find the mid point. I’ve fixed your code below. You should return the array in base condition.