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

Viewed 62544

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);
8 Answers

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.

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);
Related