10

I want to reverse an array without using reverse() function like this:

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

    return output;
}

console.log(reverse([1,2,3,4,5,6,7]));

However, the it shows [7, 6, 5, 4] Can someone tell me, why my reverse function is wrong? Thanks in advance!

4
  • what do you want it to show you? Commented Nov 22, 2016 at 20:42
  • 1
    How are there this many answers to this question? None of which mention reversing in place. stackoverflow.com/questions/5276953/… has Commented Nov 22, 2016 at 20:47
  • 2
    @axlj, "how are there this many answers..." because there's more than one way to skin a cat, and in this case reverse the cat as well. Commented Nov 22, 2016 at 20:59
  • @zzzzBov I should have clarified -- ... Identical answers :-) Commented Nov 22, 2016 at 21:18

31 Answers 31

1
2
-1

Array=[2,3,4,5]

 for(var i=0;i<Array.length/2;i++){
    var temp =Array[i];
    Array[i]=Array[Array.length-i-1]
    Array[Array.length-i-1]=temp
}

console.log(Array) //[5,4,3,2]

Sign up to request clarification or add additional context in comments.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.