Created
October 26, 2021 18:34
-
-
Save Elijah-trillionz/fd04a8e908be9b2c8ba993e523e99f87 to your computer and use it in GitHub Desktop.
Reversing javascript arrays without the reverse method
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
// reverse an array that modifies the array | |
function reverseArrayInPlace(arr) { | |
let length = arr.length; | |
for (let i = length - 1; i >= 0; i--) { | |
arr.push(arr[i]); | |
} | |
arr.splice(0, length); | |
return arr; | |
} | |
// reverse an array that creates a new array with push method | |
function reverseArray(arr) { | |
const newArr = []; | |
for (let i = arr.length - 1; i >= 0; i--) { | |
newArr.push(arr[i]); | |
} | |
return newArr; | |
} | |
// reverse an array that creates a new array with unshift method | |
function reverseArray(arr) { | |
const newArr = []; | |
for (let i = 0; i < arr.length; i++) { | |
newArr.unshift(arr[i]); | |
} | |
return newArr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment