Why doesn't this .slice method work? Working in Eloquent Javascript, Chapter 4

Viewed 20

Trying a tutorial from Eloquent Javascript, creating a function that Reverses Array In Place (i.e. without storing value in a new array). I have since solved using other methods, but still don't understand why my slicing doesn't seem to work.

function reverseArrayInPlace(array) {
  let count = 0;
  
  for (let i = array.length - 1; i >= 0; i--) {
    array.push(array[i]);
    count++
  }
  
  return array.slice(count)
}

console.log(reverseArrayInPlace(["a", "b", "c"]))

I don't understand why I can't successfully return the array sliced as the final step - instead it's returning the entire array [

This push method successfully added the values in the reverse order - and the count variable successfully tracks the index where the slice would need to take place. I would like to have the final action of function slice the array and store is as this newly sliced array.

Not interested in other methods to solve - interested why this slicing won't work, please!

1 Answers

This isn't reversing in place. It appends the reversed elements to the end of the original array, then returns a new array containing that slice. If you log the original array, you'll see both the original and reversed contents.

You can use splice() to remove the original elements, then return the updated array.

function reverseArrayInPlace(array) {
  let count = array.length;
  
  for (let i = array.length - 1; i >= 0; i--) {
    array.push(array[i]);
  }
  array.splice(0, count); // remove the original elements
  return array;
}

let a = ["a", "b", "c"];
console.log(reverseArrayInPlace(a));
console.log(a);

Related