Created
February 18, 2017 06:07
-
-
Save Spec007/c3392ecccc87554f72ef412f876d73ba to your computer and use it in GitHub Desktop.
Eloquent Javascript: Reversing an Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 in order to reverse its elements. Neither may use | |
the standard reverse method. */ | |
function reverseArray(array) { | |
var newArray = []; | |
for (var i = 0; i < array.length; i++) { | |
newArray.unshift(array[i]); | |
} | |
return newArray; | |
} | |
function reverseArrayInPlace(array) { | |
var temp = []; | |
for (var i = 0; i < Math.floor(array.length/2);i++) { | |
temp[i] = array[i]; //save first part of array, so it won't be overwritten | |
array[i] = array[array.length - 1 - i]; //replace one of the elements in the first half of the array with the corresponding element in the back half of the array | |
array[array.length - 1 - i] = temp[i]; //replace one of the elements in the back half of the array with the corresponding element in the first half of the array that was placed in safekeeping in a temporary variable | |
} | |
return array; | |
} | |
console.log(reverseArray(["A", "B", "C"])); | |
// → ["C", "B", "A"]; | |
var arrayValue = [1, 2, 3, 4, 5]; | |
reverseArrayInPlace(arrayValue); | |
console.log(arrayValue); | |
// → [5, 4, 3, 2, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment