Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Created May 1, 2018 06:02
Show Gist options
  • Save Luke-Rogerson/cca5ba3e7e3f5c86fb618d7830974ded to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/cca5ba3e7e3f5c86fb618d7830974ded to your computer and use it in GitHub Desktop.
ReversingAnArray created by Luke_Rogerson - https://repl.it/@Luke_Rogerson/ReversingAnArray
// Eloquent Javascript, Chapter 4, Coding Challenge #2
/*Arrays have a reverse method which changes the array by inverting the order in which its elements appear. For this exercise, write two functions, reverseArray and reverseArrayInPlace. The first, reverseArray, takes an array as argument and produces a new array that has the same elements in the inverse order. The second, reverseArrayInPlace, does what the reverse method does: it modifies the array given as argument by reversing its elements. Neither may use the standard reverse method.*/
function reverseArray (array) {
let newArray = [];
for (let i = array.length; i >= 0; i--) {
newArray.push(i);
}
return newArray;
}
function reverseArrayInPlace (array) {
for (let i = 0; i < Math.floor((array.length)/2); i++) {
let temp;
temp = array[i];
array[i] = array[array.length-1-i];
array[array.length-1-i] = temp;
}
return array;
}
reverseArrayInPlace([1,2,3,4,5,6,7,8,9]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment