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]
3 Answers 3
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
1 Comment
arr is dropped. Remove arr = and it will still work. 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.
4 Comments
arr will also change it outside the function but arr = /* something */ would not affect the array outside the function.console.log(reverseArrayInPlace(b)); the method must return it, otherwise the value printed will always be undefined because the function does not return anythingBecause the array is passed to the function by copying the reference, hence you cannot change the external reference from inside the function.
return arrat the end, you'll see it works.