Skip to content

Instantly share code, notes, and snippets.

@Elijah-trillionz
Created October 26, 2021 18:34
Show Gist options
  • Save Elijah-trillionz/fd04a8e908be9b2c8ba993e523e99f87 to your computer and use it in GitHub Desktop.
Save Elijah-trillionz/fd04a8e908be9b2c8ba993e523e99f87 to your computer and use it in GitHub Desktop.
Reversing javascript arrays without the reverse method
// 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