Question

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?

Was it helpful?

Solution

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/

OTHER TIPS

try this:

mainArray.splice(0, 1, ...arraysToAdd)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top