0

I'm trying to reverse the order of an array using the .reverse() method in JavaScript, but also trying to preserve the original order of elements in the original array. When I save the values into a variable, I end up transposing the elements in the original array as well as creating a new one with the same format. What is the most eloquent way to perform this task?

var arrayOne = [1,2,3,4,5]; var arrayTwo = arrayOne.reverse(); //arrayTwo = [5, 4, 3, 2, 1] //arrayOne = [5, 4, 3, 2, 1] 
4
  • 2
    do you need it actually reversed on a separate variable or could you just iterate backwards from its length property? Commented Apr 22, 2015 at 15:53
  • 1
    You'd have to make a clone. The reverse method is a mutative method, so the original array gets changed. Simply setting another array to it wont preserve it Commented Apr 22, 2015 at 15:54
  • See stackoverflow.com/questions/15722433/… about the slice method Commented Apr 22, 2015 at 15:55
  • More duplicate of stackoverflow.com/questions/23666679/… Commented Apr 22, 2015 at 16:00

1 Answer 1

8
var arrayTwo = arrayOne.slice().reverse(); 

Slice will clone the array

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

3 Comments

This question would obviously be a duplicate. Next time please find the dup and close. You have the rep to do so
Thank you @jcubic and Ramón Gil Moreno, I'd give you an upvote for educating me, but as mplungjan put in such a snark manner, while my rep of "ONE" allows me to spend countless hours looking through the hundreds of related questions, it inhibits my ability to return the favor of enlightening me. I appreciate it. Seriously the most annoying thing about Stack Overflow.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.