A better way to splice an array into an array in javascript

JavascriptArrays

Javascript Problem Overview


Is there a better way than this to splice an array into another array in javascript

var string = 'theArray.splice('+start+', '+number+',"'+newItemsArray.join('","')+'");';
eval(string);

Javascript Solutions


Solution 1 - Javascript

You can use apply to avoid eval:

var args = [start, number].concat(newItemsArray);
Array.prototype.splice.apply(theArray, args);

The apply function is used to call another function, with a given context and arguments, provided as an array, for example:

If we call:

var nums = [1,2,3,4];
Math.min.apply(Math, nums);

The apply function will execute:

Math.min(1,2,3,4);

Solution 2 - Javascript

UPDATE: ES6 version

If you're coding in ES6, you can use the "spread operator" (...).

array.splice(index, 0, ...arrayToInsert);

To learn more about the spread operator see the MDN documentation.


The 'old' ES5 way

If you wrap the top answer into a function you get this:

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}

You would use it like this:

var arr = ["A", "B", "C"];
insertArrayAt(arr, 1, ["x", "y", "z"]);
alert(JSON.stringify(arr)); // output: A, x, y, z, B, C

You can check it out in this jsFiddle: http://jsfiddle.net/luisperezphd/Wc8aS/

Solution 3 - Javascript

This question is really old, but with ES6, there's a simpler way to do this using the spread operator:

sourceArray.splice(index, 0, ...insertedArray)

If you're using uncompiled javascript in the browser, be sure to check if it's supported in your target browser at https://kangax.github.io/compat-table/es6/#test-spread_(...)_operator.


Also, this may be slightly off topic, but if you don't want or need to modify the original array, but could use a new array instead, consider this approach:

mergedArray = sourceArray.slice(0, index).concat(insertedArray, sourceArray.slice(index))

Solution 4 - Javascript

You can also add such a function to the Array prototype, if you want something that is almost identical to the splice method. E.g.

Array.prototype.spliceArray = function(index, n, array) {
    return Array.prototype.splice.apply(this, [index, n].concat(array));
}

Then usage would simply be:

var array = ["A","B","C","","E","F"];

array.splice(3,1,"D");
// array is ["A","B","C","D","E","F"]

array.spliceArray(3,3,["1","2","3"]);
// array is ["A","B","C","1","2","3"]

See it in action here: http://jsfiddle.net/TheMadDeveloper/knv2f8bb/1/

Some notes:

  • The splice function modifies the array directly, but returns the an array of elements that were removed... not the spliced array.
  • While it's normally not recommended to extend core javascript classes, this is relatively benign with most standard frameworks.
  • Extending Array won't work in cases where specialized array classes are used, such as an ImageData data Uint8ClampedArray.

Solution 5 - Javascript

The answers above that involve splice.apply and insert the array in a one liner will blow up the stack in a stack overflow for large array. See example here: http://jsfiddle.net/gkohen/u49ku99q/ You might have to slice and and push each item of the inserted and remaining part of the original array for it to work. See fiddle: http://jsfiddle.net/gkohen/g9abppgy/26/

Array.prototype.spliceArray = function(index, insertedArray) {
   var postArray = this.splice(index);
   inPlacePush(this, insertedArray);
   inPlacePush(this, postArray);

   function inPlacePush(targetArray, pushedArray) {
// Not using forEach for browser compatability
       var pushedArrayLength = pushedArray.length;
       for (var index = 0; index < pushedArrayLength; index++) {
           targetArray.push(pushedArray[index]);
       }
   }
}

Solution 6 - Javascript

There are a lot of clever answers here, but the reason you use splice is so that it puts the elements into the current array without creating another. If you have to create an array to concat() against so you can use apply() then you're creating 2 additional trash arrays! Sorta defeats the whole purpose of writing esoteric Javascript. Besides if you don't care about that memory usage stuff (and you should) just dest = src1.concat(src2); it is infinitely more readable. So here's is my smallest number of lines while staying efficient answer.

for( let item of src ) dest.push( item );

Or if you'd like to polyfill it and have a little better browser support back:

src.forEach( function( x ) { dest.push(x); });

I'm sure the first is more performant (it's a word ;), but not supported in all browsers out there in the wild.

Solution 7 - Javascript

If you don't want to concatenate inserting items to first two parameters of Array.splice(), an elegant way is to use Function.bind() and Function.apply() together.

theArray.splice.bind(null, startIndex, deleteCount).apply(newItemsArray);

Solution 8 - Javascript

I wanted to have a function which would take only part of the source array so I have mine slightly different based off CMS's answer

function spliceArray(array, index, howmany, source, start, end) {
	var arguments;
  if( source !== undefined ){
  	arguments = source.slice(start, end);
    arguments.splice(0,0, index, howmany);
  } else{
   arguments = [index, howmany];
  }
	return Array.prototype.splice.apply(array, arguments)
}

Array.prototype.spliceArray = function(index, howmany, source, start, end) {
    return spliceArray(this, index, howmany, source, start, end);
}

You can see it at: https://jsfiddle.net/matthewvukomanovic/nx858uz5/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwheresrhysView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptLuis PerezView Answer on Stackoverflow
Solution 3 - JavascriptundefinedView Answer on Stackoverflow
Solution 4 - JavascriptTheMadDeveloperView Answer on Stackoverflow
Solution 5 - JavascriptGabriel KohenView Answer on Stackoverflow
Solution 6 - JavascriptchubbsondubsView Answer on Stackoverflow
Solution 7 - JavascriptSen JacobView Answer on Stackoverflow
Solution 8 - JavascriptMatt VukomanovicView Answer on Stackoverflow