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.

5
  • Side note: doNotForgetTheLowerCamelCase :) Commented Aug 22, 2012 at 12:28
  • There's a difference between .splice() and .slice() ... Commented Aug 22, 2012 at 12:28
  • @sp00m: I like PascalNotation; I just think it looks better. Commented Aug 22, 2012 at 12:32
  • 2
    @frenchie I'm talking about conventions. PascaleNotation is reserved for classes, whereas lowerCamelCase is used for methods/functions and variables/attributes/properties. Commented Aug 22, 2012 at 12:34
  • @sp00m: I know about conventions but I really do prefer the looks of PascalNotation. Commented Aug 22, 2012 at 12:50

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

5

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]

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.