Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript reverse an array without using reverse()

Tags:

javascript

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!

like image 613
Zichen Ma Avatar asked Nov 22 '16 20:11

Zichen Ma


People also ask

How do you reverse an array without using .reverse in JavaScript?

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

How do you reverse an array without changing the original array?

To reverse an array without modifying the original, call the slice() method on the array to create a shallow copy and call the reverse() method on the copy, e.g. arr. slice(). reverse() . The reverse method will not modify the original array when used on the copy.

How do you reverse an array in JavaScript?

JavaScript Array reverse()The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.


1 Answers

array.pop() removes the popped element from the array, reducing its size by one. Once you're at i === 4, your break condition no longer evaluates to true and the loop ends.


One possible solution:

function reverse(array) {
  var output = [];
  while (array.length) {
    output.push(array.pop());
  }

  return output;
}

console.log(reverse([1, 2, 3, 4, 5, 6, 7]));
like image 125
TimoStaudinger Avatar answered Oct 04 '22 15:10

TimoStaudinger