Skip to content

Instantly share code, notes, and snippets.

@abdulhalim-cu
Created November 4, 2017 12:39
Show Gist options
  • Select an option

  • Save abdulhalim-cu/9f4dcc2baf228ffdc19ddef4290d88ef to your computer and use it in GitHub Desktop.

Select an option

Save abdulhalim-cu/9f4dcc2baf228ffdc19ddef4290d88ef 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…
// Your code here.
function reverseArray(array){
var arr_list = [];
for (var i = array.length - 1; i >= 0; i--) {
arr_list.push(array[i]);
}
return arr_list;
}
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
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