Dr_V
Dr_V

Reputation: 25

Array reversing function JS

A beginner JS question.. I need to write a function that reverses an array that goes as a function's input. (I cannot use a reverse method).

I wonder why this works:

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

But this does NOT:

function reverseArrayInPlace(arr) {
  let len = arr.length;
  for (counter = 0; counter < 2 * len; counter += 2) {
    arr.unshift(arr[counter]);
  }
  arr = arr.slice(0, len);
}
let b = [0, 1, 2, 3, 4, 5];
console.log(reverseArrayInPlace(b));

Looks like arr = arr.slice(0,len); part is not working..I wonder why when:

b = b.slice(0,6);
[5, 4, 3, 2, 1, 0]

Upvotes: 0

Views: 125

Answers (3)

quirimmo
quirimmo

Reputation: 9988

If you want to change the input arrray, avoiding return, use splice:

function reverseArrayInPlace(arr) {
  let len = arr.length;
  for (counter = 0; counter < 2 * len; counter += 2) {
    arr.unshift(arr[counter]);
  }
  arr.splice(len);
}
var b = [0, 1, 2, 3, 4, 5];
reverseArrayInPlace(b);
console.log(b);

EDIT:

If you want to do something like:

console.log(reverseArrayInPlace(b));

your function MUST return something, otherwise the print will always be undefined, even if b has been reverted

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

   arr = arr.slice(0, len);

slice returns a new array which you store inside the local variable arr, that does not change b, which is still pointing to the whole array. To mutate the array you could:

 arr.splice(len, len);

and then you have to return arr to log something meaningful.

Upvotes: 1

Daniele Debernardi
Daniele Debernardi

Reputation: 21

Because the array is passed to the function by copying the reference, hence you cannot change the external reference from inside the function.

Upvotes: 0

Related Questions