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.
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.
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.
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() .
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.
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));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With