Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 215
Smash Avatar asked Dec 19 '13 18:12

Smash


People also ask

How do you remove an element from an array in another array?

For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.

How do you remove an element from an array and return a new array?

To remove one or more elements from an array, use the splice() method. The splice method changes the contents of the original array by removing, replacing or adding new elements and returns an array containing the removed elements.

Can you add or remove elements of an array once it's created?

Once an array is created, its size cannot be changed. If you want to change the size, you must create a new array and populates it using the values of the old array. Arrays in Java are immutable. To add or remove elements, you have to create a new array.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


2 Answers

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

var m2 = m1.slice(0);
like image 77
Julio Avatar answered Sep 28 '22 00:09

Julio


Use Array.prototype.slice to copy arrays:

var m2 = m1.slice();
like image 21
VisioN Avatar answered Sep 27 '22 22:09

VisioN