Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array in which all the elements are also arrays (of integers), called mainArray. I am trying to use splice() to add and remove its elements (subarrays).

Initially mainArray has a single element (an Array with one integer), I wish to delete it and add 3 new subarrays to mainArray, these are defined in arraysToAdd.

mainArray = new Array(new Array(1));
arraysToAdd = new Array(new Array(1,2), new Array(1,4), new Array(1,7));

alert(arraysToAdd.length); // Returns: 3: as expected

mainArray.splice(0,1,arraysToAdd);

alert(mainArray.length); // Returns: 1: I want this to be 3

I expect the length of mainArray at the end to be 3 (as it should contain 3 subarrays), but it seems splice() is flattening arraysToAdd and so mainArray ends up just being an array of integers.

What am I missing?

share|improve this question
1  
console.log(mainArray) –  zerkms Feb 24 at 0:44
    
"but it seems splice() is flattening arraysToAdd" Uhm, how can the length of mainArray be 1 if the other arrays is flattened into mainArray? If mainArray was an array of integers, wouldn't the length be 6? –  Felix Kling Feb 24 at 0:46
2  
You do know you can just type var mainArray = [[1]];, right? –  PHPglue Feb 24 at 0:51
    
@PHPglue brings up a good point. In fact, your mainArray worked because you didn't use the value, but if you had tried to use it, or if you created it with a greater number, you'd get a result that you may not expect. Like if you did new Array(3), you now have an Array with .length === 3, and no actual defined members. –  cookie monster Feb 24 at 1:58

1 Answer 1

up vote 5 down vote accepted

What you're missing is that you're adding an Array of Arrays to your Array of Arrays. You want to add each individual Array instead.

You can use .apply() to do this:

mainArray.splice.apply(mainArray, [0,1].concat(arraysToAdd));

So the 0 and 1 arguments you passed are joined with your arraysToAdd to form the arguments that you're going to pass to .splice() via .apply().

Demo: http://jsfiddle.net/QLwLA/


Without .apply(), you would have needed to add them individually, like this:

mainArray.splice(0, 1, arraysToAdd[0], arraysToAdd[1], arraysToAdd[2]);

Demo: http://jsfiddle.net/QLwLA/1/

share|improve this answer
    
brilliant, thanks –  jacobianism Feb 24 at 0:48
    
You're welcome. –  cookie monster Feb 24 at 0:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.