Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use Array.splice in javascript with the third parameter as an array?

Tags:

I'm attempting the following:

var a1 = ['a', 'e', 'f'];  // [a, e, f] var a2 = ['b', 'c', 'd'];  // [b, c, d] a1.splice(1, 0, a2);       // expected [a, b, c, d, e, f]                            // actual (a, [b, c, d], e, f] 

I am confined in my use case by having a2 exist as an array of indeterminant size. Does anyone know of a way to feed splice an array as the substitution, or alternatively a built-in function to do this? I know I could iterate over the elements of a2 and splice them in one at a time, but I'd prefer the fastest method possible because I will need to do this a lot.

like image 623
CoryG Avatar asked Feb 05 '13 19:02

CoryG


People also ask

What is the alternative of splice in JavaScript?

Alternative of Array splice() method in JavaScript If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends.

How do you splice an array inside an array?

Use the array methods slice and splice to copy each element of the first array into the second array, in order. Begin inserting elements at index n of the second array. Return the resulting array. The input arrays should remain the same after the function runs.

Does splice work on arrays?

splice() The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice() .

How does array splice work in JavaScript?

splice() JS Array Method. The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.


2 Answers

Array.splice supports multiple arguments after the first two. Those arguments will all be added to the array. Knowing this, you can use Function.apply to pass the array as the arguments list.

var a1 = ['a', 'e', 'f']; var a2 = ['b', 'c', 'd'];  // You need to append `[1,0]` so that the 1st 2 arguments to splice are sent Array.prototype.splice.apply(a1, [1,0].concat(a2)); 
like image 62
Rocket Hazmat Avatar answered Sep 30 '22 14:09

Rocket Hazmat


With ES6, you can use the spread operator. It makes it much more concise and readable.

var a1 = ['a', 'e', 'f'];  var a2 = ['b', 'c', 'd'];    a1.splice(1, 0, ...a2);  console.log(a1)
like image 24
maazadeeb Avatar answered Sep 30 '22 12:09

maazadeeb