Created
February 6, 2018 17:04
-
-
Save jonurry/eba469450f5583d71f30077984b995a5 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
The answer to my previous question is simple:
let arr = [1, 2, 3, 4, 5]; function reverseArrayInPlace(arr) { for (let i of [...arr]) { arr.unshift(i); arr.pop(); } return arr; } reverseArrayInPlace(arr); console.log(arr); //result=> [5, 4, 3, 2, 1]
In this snippet, the reverseArrayInPlace function attempts to reverse the elements of the array by iteratively removing the last element of the array and inserting it at the beginning using unshift and pop operations. However, the loop for (let i of [...arr]) creates a new array arr using the spread operator [...arr], which effectively creates a shallow copy of the original array arr. Therefore, the loop iterates over the shallow copy of the original array in its original order and reverses the original array. Consequently, the output will be [5, 4, 3, 2, 1].
let arr = [1, 2, 3, 4, 5]; function reverseArrayInPlace(arr) { for (let i of arr) { arr.unshift(i); arr.pop(); } return arr; } reverseArrayInPlace(arr); console.log(arr); //result=> [1, 1, 1, 1, 1]
In this snippet, the reverseArrayInPlace function also attempts to reverse the elements of the array using the same approach. However, in this case, the loop for (let i of arr) directly iterates over the original array arr. The issue with this code is that modifying an array while iterating over it.