3

I have a global array like:

var myArray = [];

And it has various elements in it. I need to create a new array with the same contents and then reverse it like this:

newArray = myArray;
newArray = newArray.reverse();

However when I do this, it reverses both the myArray and newArray.

What am I doing wrong?

Thanks!

2
  • 2
    Depends on what you have in array. If it's simple primitive values like numbers, then .slice is enough to clone an array. If you have objects in array, you have to make a deep copy of array, and slice will make only a shallow copy. If it's what you need then use .slice method. Commented Nov 13, 2014 at 6:45
  • 1
    jsfiddle.net/450bd6wj Commented Nov 13, 2014 at 6:46

1 Answer 1

5

It's because both your arrays are referenced to the same object. To get rid of it you have to clone it with slice..

var myArray = [1,2];
var newArray = myArray.slice(0)
newArray.reverse();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.