Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversed array does not contain every element

Why does my function return only [3, 2,]. It should print out the element 1 as well?

function reverseArr(arr) {
    var reverse = [];
    for (var i = 0; i < arr.length; i++)
        reverse.push(arr.pop());
    return reverse;
}

console.log(reverseArr([1, 2, 3]));
like image 606
DEdesigns57 Avatar asked Jan 10 '23 00:01

DEdesigns57


2 Answers

Because you're modifying arr with each iteration, arr.length is changing. Try this instead:

function reverseArr(arr) {
    var reverse = [], len = arr.length;
    for (var i = 0; i < len; i++)
        reverse.push(arr.pop());
    return reverse;
}

Note, however, this will modify the original array, which is probably not what you intended. If you'd like to preserve the original array, use unshift instead:

function reverseArr(arr) {
    var reverse = [], len = arr.length;
    for (var i = 0; i < len; i++)
        reverse.unshift(arr[i]);
    return reverse;
}

Alternatively, you can use a combination of slice and reverse to return a new, reversed copy of the input array without modifying the original:

function reverseArr(arr) {
    return arr.slice().reverse();
}
like image 187
p.s.w.g Avatar answered Jan 21 '23 15:01

p.s.w.g


The problem is that you're changing the length of the array as you pop off of it. So arr.length starts at 3 then 2 then 1. Instead, you could do something like this:

function reverseArr(arr) {
    var reverse = [];
    while (arr.length) {
        reverse.push(arr.pop());
    }
    return reverse;
}
like image 43
Mike Cluck Avatar answered Jan 21 '23 14:01

Mike Cluck