Reverse Arrays
by David Hughes
JavaScript
var array = [5, 4, 3, 2, 1];
//Reverse array and output to new array
function reverseArray(arr) {
var output = [];
for (var i = arr.length - 1; i >= 0; i--) {
output.push(arr[i]);
}
return output;
}
//Reverse array in place
function reversedArray(arr) {
console.log("The original array was: " + array);
for (var i = 0; i < arr.length; i++) {
//Pop last element off the array, store in popped
var popped = arr.pop();
//Add "popped" to the "i"th index of the array
arr.splice(i, 0, popped);
}
console.log("The new array is: " + arr);
return arr;
}
reversedArray(array);