How to insert an array inside another array?

I have 2 arrays:

var str = ['a','b','c','d'];
var num = [1,2,3];

I want to have an array like this:

var strNum= ['a','b',1,2,3,'c','d'];

is there a method for this?

+4
source share
5 answers

You may be looking for the following:

var str = ['a','b','c','d'];
var num = [1,2,3];

var startAt = 2;
num.forEach((number, ind)=>{
    str.splice(startAt+ind, 0, number);
});

console.log(str);

https://jsfiddle.net/qbkqspqq/

+2
source

you can use Array#splice

The method modifies the contents of the array by deleting existing elements and / or adding new elements. splice()

with Function.apply

The method apply()calls a function with a given value thisand argumentsprovided as an array (or a massive object ).

var str = ['a', 'b', 'c', 'd'],
    num = [1, 2, 3],
    strNum = str.slice();

Array.prototype.splice.apply(strNum, [2, 0].concat(num));
console.log(strNum);
Run code

Or you can use ES6 distribution syntax...

, ( ) ( ) ( ).

var str = ['a', 'b', 'c', 'd'],
    num = [1, 2, 3],
    strNum = str.slice();

strNum.splice(2, 0, ...num);
console.log(strNum);
+7

- splice. str.splice(index, 0, item); item str ( 0 , ).

splice() , / .

: Array.splice

, :

var str = ['a','b','c','d'];
var num = [1,2,3];
for(i in num.reverse()){
  str.splice(2, 0, num[i]);
}
console.log(str);

:

var str = ['a','b','c','d'];
var num = [1,2,3];
str=str.slice(0,2).concat(num).concat(str.slice(-2));
console.log(str);
+6

. , :

var str = ['a','b','c','d'];
var num = [1,2,3];

var where = 2;
var result = [].concat(
    str.slice(0, where), 
    num, 
    str.slice(where));

console.log(result)
+1

You can use the method sliceto split the array strinto 2: part before the insertion point and part after:

var before = str.slice(0,2);
var after = str.slice(2);

Then you can use the method concatto create an array strNum, combining arrays before, numand afterinto one:

var strNum = before.concat(num).concat(after);

var str = ['a','b','c','d'];
var num = [1,2,3];

var before = str.slice(0,2);
var after = str.slice(2);

var strNum = before.concat(num).concat(after);

console.log(strNum);
Run code
0
source

Source: https://habr.com/ru/post/1664264/


All Articles