insert an array inside another array
What is the more efficient way to insert an array inside another array.
a1 = [1,2,3,4,5];
a2 = [21,22];
newArray - a1.insertAt(2,a2) -> [1,2, 21,22, 3,4,5];
Iterating a2 using splice looks a bit awfull from a performance point of view if a2 array is large.
Thanks.
You can use splice
combined with some apply
trickery:
a1 = [1,2,3,4,5];
a2 = [21,22];
a1.splice.apply(a1, [2, 0].concat(a2));
console.log(a1); // [1, 2, 21, 22, 3, 4, 5];
In ES2015+, you could use the spread operator instead to make this a bit nicer
a1.splice(2, 0, ...a2);
Had it wrong at first. Should have used concat()
instead.
var a1 = [1,2,3,4,5];
var a2 = [21,22];
var result = a1.slice( 0, 2 ).concat( a2 ).concat( a1.slice( 2 ) );
Example: http://jsfiddle.net/f3cae/1/
This takes a slice()
[docs] of a1
up to the index, then does a concat()
[docs] to add a2
to that array, then uses .concat()
again taking another .slice()
of a1
, but this time starting at the same index through the end.
And add it to Array.prototype
if you wish:
Example: http://jsfiddle.net/f3cae/2/
Array.prototype.injectArray = function( idx, arr ) {
return this.slice( 0, idx ).concat( arr ).concat( this.slice( idx ) );
};
var a1 = [1,2,3,4,5];
var a2 = [21,22];
var result = a1.injectArray( 2, a2 );
You can use the splice()
[docs] method without iterating.
a1.splice( 2, 0, a2 );
http://jsfiddle.net/f3cae/
You can now do this if using ES2015 or later:
var a1 = [1,2,3,4,5];
var a2 = [21,22];
a1.splice(2, 0, ...a2);
console.log(a1) // => [1,2,21,22,3,4,5]
Refer to this for documenation on the spread (...) operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
链接地址: http://www.djcxy.com/p/29324.html下一篇: 在另一个数组中插入一个数组