1

I'm studying JS and I have this exercise that is asking to reverse an array in place (without the use of a second array) and without the use of 'reverse'. Although I already have the solution to the exercise I don't understand why my solution does not work, here it is:

function reverseArrayInPlace (arr){
  const k = arr[0];
  while (arr[arr.length-1] !== k){
    arr.unshift(arr.pop());
    }
  return arr;

}

console.log(reverseArrayInPlace(arr1));

3
  • What if you try to reverse [0, 1, 2, 0] ? then the loop won't run as arr[0] === arr[arr.length - 1] ... Commented Feb 13, 2019 at 6:04
  • Can you give example of how it doesn't work? As in - the input and expected output? Commented Feb 13, 2019 at 6:06
  • output is: [11,12,13,14,15,16,17,18,19,20,10] in my understanding when the loop starts the value of arr.pop() should go at the beginning or arr until last value of arr is equal to original initial value. But it does not happen Commented Feb 13, 2019 at 6:17

4 Answers 4

1

You take the end of the array and put it at the first position:

 [1, 2, 3]
 [3, 1, 2]
 [2, 3, 1]
 [1, 2, 3]

as you can see that actually doesnt reverse anything.

Sign up to request clarification or add additional context in comments.

1 Comment

oohh gosh..silly me.. I see that now... so my function is working but not the way it should... many thanks
0

It will not work if your array contains duplicates of the first element. As you are taking the first element as key, whenever any duplicate element becomes the last element, your loop exits.

Comments

0

Try this, just check if the two elements being selected is equal or not, if equal do not swap else swap. Iterate till the pointer k is <= the pointer j.

function reverseArrayInPlace (arr){
  let first = 0;
  let last = arr.length - 1;
  let k = first, j = last;
  while(k <= j){
    if(arr[k] !== arr[j]){
      let temp = arr[k];
      arr[k] = arr[j];
      arr[j] = temp;
    }
    k++;
    j--;
  }
  return arr;
}
arr1 = [1, 2, 3, 4];
console.log(reverseArrayInPlace(arr1));
arr1 = [1, 2, 3];
console.log(reverseArrayInPlace(arr1));

Comments

0

This method will solve the problem without pop or unshift. Try this.

 function reverseArray(array) {
 for (let i = 0; i < Math.floor(array.length / 2); i++) {
 let oldArray = array[i];
 array[i] = array[array.length - 1 - i];
 array[array.length - 1 - i] = oldArray;
 }
 return array;
 }
 console.log(reverseArray([1,2,3]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.