I am trying a JavaScript challenge. Not to use standard array reverse
method but instead creating a new function to modify an array that given as argument and reverse its elements. Here is the example:
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
However, I created this function but it didn't work:
function reverseArrayInPlace(arr) {
var newArr = [];
for (var i = arr.length - 1; i >= 0; i--) {
newArr.push(arr[i]);
}
arr = newArr; //This reverse arr successfully but won't work when called
return arr;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [1, 2, 3, 4, 5], why? The arr variable above returned [5, 4, 3, 2, 1] but not here
This is the answer and it worked:
function reverseArrayInPlace(arr) {
for (var i = 0; i < Math.floor(arr.length / 2); i++) {
var old = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = old;
}
return arr;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
What is wrong with my method. What I don't get is the console.log
did output the right reverse order but it will still show the original arrayValue
when output. Can someone explain the difference to me?