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]
enterloper
  • 16
  • 1
  • 5
  • 2
    do you need it actually reversed on a separate variable or could you just iterate backwards from its length property? – Rooster Apr 22 '15 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 – Sterling Archer Apr 22 '15 at 15:54
  • See http://stackoverflow.com/questions/15722433/javascript-copy-array-to-new-array about the slice method – Ramón Gil Moreno Apr 22 '15 at 15:55
  • More duplicate of http://stackoverflow.com/questions/23666679/making-an-independent-copy-of-a-reversed-array-in-javascript – jcubic Apr 22 '15 at 16:00

1 Answers1

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

Slice will clone the array

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 2
    Yup. Note that it is a shallow copy: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice – Ramón Gil Moreno Apr 22 '15 at 15:56
  • This question would obviously be a duplicate. Next time please find the dup and close. You have the rep to do so – mplungjan Apr 22 '15 at 15:58
  • 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. – enterloper Apr 22 '15 at 16:31