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

7

25

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.

Lionellionello answered 5/2, 2013 at 19:35 Comment(0)
W
37

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));
Waltraudwaltz answered 5/2, 2013 at 19:41 Comment(0)
A
23

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)
Alliterate answered 25/10, 2017 at 8:56 Comment(0)
S
4
var a1 = ['a', 'e', 'f'],
    a2 = ['b', 'c', 'd'];

a1.splice(1, 0, a2);

var flatten = [].concat.apply([], a1); // ["a", "b", "c", "d", "e", "f"]
Shareeshareholder answered 5/2, 2013 at 19:42 Comment(0)
R
2

This should do the trick.

var a1 = ['a', 'e', 'f'];
var a2 = ['b', 'c', 'd'];

a1.concat(a2, a1.splice(1,a1.length-1)) // [a, b, c, d, e, f]
Refutation answered 5/2, 2013 at 19:46 Comment(0)
E
1

Try this:

var params = a2.slice(0);
params.unshift(1,0);
a1.splice.apply(a1,params);

In the more general case:

Array.prototype.splice_multi = function(offset,todelete,insert) {
    var params = insert.slice(0);
    params.unshift(offset,todelete);
    return this.splice.apply(this,params);
};
a1.splice_multi(1,0,a2);
Euniceeunuch answered 5/2, 2013 at 19:42 Comment(0)
P
0
Array.prototype.splice.apply( [1,2,3], [2, 0].concat([4,5,6]) );
Parsaye answered 2/8, 2013 at 16:23 Comment(0)
S
0
private moveElements(source: Array<any>, target: Array<any>) {
    target.push(...source);
    source.splice(0, source.length);
    //or
    [].push.apply(target,source);
    source.splice(0, source.length);
}
Subequatorial answered 28/7, 2016 at 13:47 Comment(1)
Please add some explanation to the answer.Disaffection

© 2022 - 2024 — McMap. All rights reserved.