Forked from jonurry/4-2 Eloquent Javascript Solutions.js
Created
December 2, 2022 10:27
-
-
Save VladimirMakarof/57b44286b71f6ee6a20fb6f5b056073e to your computer and use it in GitHub Desktop.
4.2 Reversing an Array (Eloquent JavaScript Solutions)
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
function reverseArray(array) { | |
result = []; | |
for (let item of array) { | |
result.unshift(item); | |
} | |
return result; | |
} | |
function reverseArrayInPlace(array) { | |
let len = array.length; | |
for (let i = 0; i < Math.floor(len/2); i++) { | |
console.log(i, len-i-1, array[i], array[len-i-1], array); | |
let swap = array[i]; | |
array[i] = array[len-i-1]; | |
array[len-i-1] = swap; | |
} | |
return array; | |
} | |
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] | |
let arrayValue2 = [1, 2, 3, 4]; | |
reverseArrayInPlace(arrayValue2); | |
console.log(arrayValue2); | |
// → [4, 3, 2, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment