The exercise asks to create a function, reverseArrayInPlace(), that takes an existing array and reverses its order by only using the existing array. The exercise also advises that I cannot use the reverse method for an array.
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
This is the solution that I came up with:
var arrayValue = [1, 2, 3, 4, 5];
function reverseArrayInPlace(inputArray){
for (let i = inputArray.length - 2; i >= 0; i--){
inputArray.push(inputArray[i]);
}
inputArray.splice(0, inputArray.length / 2);
}
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
Although it solves the problem posed, I want to ensure that I am not developing bad habits and that this is an acceptable solution. Would there be a more ideal way to solve this problem?