1

How can I make a reversed copy of an array using .reverse()? I can't wrap my head around this.

This is my function:

function flipArray(inputArray){
let origArray = inputArray;
let flippedArray = origArray.reverse();

console.log(inputArray);
console.log(origArray);
console.log(flippedArray);
}

flipArray([1,2,3]);

I would expect this...

[1, 2, 3]
[1, 2, 3]
[3, 2, 1]

or this...

[1, 2, 3]
[3, 2, 1]
[3, 2, 1]

but this is what I get...

[3, 2, 1]
[3, 2, 1]
[3, 2, 1]

Why does even inputArray get reversed? Is there another way to do this apart from a for loop?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse - The reverse method transposes the elements of the calling array object **in place**, mutating the array, and returning a reference to the array. – Michael Liu Sep 09 '18 at 14:14
  • Take a look [here](https://stackoverflow.com/q/7486085/86967) for more information about how to make a separate copy of an array. – Brent Bradburn Sep 09 '18 at 14:32

1 Answers1

3

Array.prototype.reverse reverse the array in-place. It modifies the original array and returns a reference to it. In order to create copies of the original array before it is reversed, you could use Array.prototype.slice, for example:

function flipArray(inputArray){

    let origArray = inputArray.slice(0);
    let flippedArray = inputArray.slice(0).reverse();

    console.log(inputArray);
    console.log(origArray);
    console.log(flippedArray);
}

flipArray([1,2,3]) now produces

[1,2,3]
[1,2,3]
[3,2,1]
bool3max
  • 2,748
  • 5
  • 28
  • 57