I'm reading through Eloquent Javascript and facing one of the exercises, I found a rather odd behavior. (at least for me)
the exercise asks to create a function in order to reverse an array. I thought I could loop over the array and each time pop one item from the original array and push it into a temporary array that is going to finally be returned. but as I'm looping over the array either with a for-of loop or typical sequential loop, last item is not transferred.
can someone tell me what happens exactly?
const reverseArray = function(array) {
let rev = [];
for (let x = 0; x <= array.length; x++) {
rev.push(array.pop());
console.log(rev, array)
}
return rev;
};
console.log(reverseArray(["A", "B", "C"]));
output:
["C"] ["A", "B"]
["C", "B"] ["A"]
["C", "B"]
When the pop() applies on array it decreases the length of the array so when the loop runs it finds one item less than the previous array length. Thus, what you can do is simply assign the length of the array in a variable and use that in the comparison of the for loop:
let rev = [];
const reverseArray = function(array) {
var length = array.length;
for (let x = 0; x < length; x++) {
rev.push(array.pop());
}
return rev;
};
console.log(reverseArray(["A", "B", "C"]));
As the pop() method remove the pop'ed item from the array, use a while loop instead of for
let rev = [];
const reverseArray = function(array) {
while (array.length > 0) { // or just "(array.length)"
rev.push(array.pop());
}
return rev;
}
console.log(reverseArray(["A", "B", "C"]));
With closure you can save yourself an extra global variable
const reverseArray = function(array) {
return (function(a_in,a_out) {
while (a_in.length > 0) { // or just "(a_in.length)"
a_out.push(a_in.pop());
}
return a_out;
})(array,[]);
}
console.log(reverseArray(["A", "B", "C"]));
Or if the Array.reverse() method is allowed
const reverseArray = function(array) {
return array.reverse();
}
console.log(reverseArray(["A", "B", "C"]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With