25

I have two arrays: ArrayA and ArrayB. I need to copy ArrayA into ArrayB (as opposed to create a reference) and I've been using .splice(0) but I noticed that it seems to removes the elements from the initial array.

In the console, when I run this code:

var ArrayA = [];
var ArrayB = [];

ArrayA.push(1);
ArrayA.push(2);

ArrayB = ArrayA.splice(0);

alert(ArrayA.length);

the alert shows 0. What am I doing wrong with .splice(0)??

Thanks for your insight.

frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

54

You want to use slice() (MDN docu) and not splice() (MDN docu)!

ArrayB = ArrayA.slice(0);

slice() leaves the original array untouched and just creates a copy.

splice() on the other hand just modifies the original array by inserting or deleting elements.

Sirko
  • 72,589
  • 19
  • 149
  • 183
7

splice(0) grabs all the items from 0 onwards (i.e. until the last one, i.e. all of them), removes them from the original array and returns them.

Imp
  • 8,409
  • 1
  • 25
  • 36
4

You are looking for slice:

var a = [1,2,3,4,5]
   ,b = a.slice();
//=> a = [1,2,3,4,5], b = [1,2,3,4,5]

you can use splice, but it will destroy your original array:

var a = [1,2,3,4,5]
   ,b = a.splice(0);
//=> a = [], b = [1,2,3,4,5]
KooiInc
  • 119,216
  • 31
  • 141
  • 177