Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
dmd3475-spring-2022/week-6/EJS-Exercises/reversing-array/main.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
26 lines (24 sloc)
983 Bytes
This file contains 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
function reverseArray(array) { | |
empty = []; | |
for(let rev of array) { | |
empty.unshift(rev); | |
} | |
return empty; | |
} | |
function reverseArrayInPlace(array){ | |
for (i = 0; i < Math.floor(array.length / 2); i++){ | |
// loops the array from 0 to the half of the array (rounded to lower number), increases i by one each time. | |
var old = array[i]; | |
//temporarely stores the current value of the array at the position i in the variable old. | |
array[i] = array[array.length - 1 - i]; | |
//sets the value of the i position to the value of the last element of the array minus the current i. | |
array[array.length - 1 - i] = old; | |
//sets the value of the last element of the array minus the current i to the previous value (stored in the old variable). | |
} | |
} | |
console.log(reverseArray(["A", "B", "C"])); | |
// → ["C", "B", "A"]; | |
let arrayValue = [1, 2, 3, 4, 5]; | |
reverseArrayInPlace(arrayValue); | |
console.log(arrayValue); | |
// → [5, 4, 3, 2, 1] |