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]