Smash
Smash

Reputation: 513

Copy to new array and remove element?

I need to copy one array and remove the element, but only from second array?

for example:

var  m1 = [ "a","b","c","d"];

var m2 = m1;

alert(m1+' and '+m2); // "a b c d" and "a b c d"

m2.splice(0,1); // b c d

alert(m1 + ' and ' + m2); // b c d and b c d

so the first element from each of these arrays was removed, but how to leave the 1st array static?

Upvotes: 6

Views: 10528

Answers (4)

Julio
Julio

Reputation: 2290

Use slice() to copy the values to the new array:

var m2 = m1.slice(0);

Upvotes: 5

Sean Doe
Sean Doe

Reputation: 275

When you assign m2 to m1, you assign reference to m2 variable. Both variables points to the same place in memory. You have to copy object.

Here is explanation how to do it in JavaScript: How do I correctly clone a JavaScript object?

Upvotes: 1

VisioN
VisioN

Reputation: 145478

Use Array.prototype.slice to copy arrays:

var m2 = m1.slice();

Upvotes: 2

Shryme
Shryme

Reputation: 1570

you need to do

var m2 = m1.slice(0);

The reason is that doing = copy the reference, slice will create a new array !

Upvotes: 1

Related Questions