Created
September 2, 2014 12:33
-
-
Save sawant/9c9e0eda73aff6167172 to your computer and use it in GitHub Desktop.
Arrays have a method reverse, 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, doe…
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
/* | |
http://eloquentjavascript.net/04_data.html | |
Arrays have a method reverse, 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 in order to reverse its elements. Neither may use the standard reverse method. | |
*/ | |
function reverseArray( array ) { | |
var reversedArray = []; | |
while( i = array.pop() ) | |
reversedArray.push( i ); | |
return reversedArray; | |
} | |
function reverseArrayInPlace( array ) { | |
for( var i = 0; i < Math.floor( array.length/2 ); i++ ) { | |
var temp = array[i]; | |
array[i] = array[array.length - 1 - i]; | |
array[array.length - 1 - i] = temp; | |
} | |
} | |
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