Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste array inside other array? [duplicate]

I have 2 arrays:

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

I want to have one array like this:

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

is there method for it?

like image 344
Serhiy Avatar asked Dec 04 '22 23:12

Serhiy


2 Answers

You could use Array#splice

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

with Function.apply

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like 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);

Or you could use ES6's spread syntax ...

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables  (for destructuring assignment) are expected.

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

strNum.splice(2, 0, ...num);
console.log(strNum);
like image 72
Nina Scholz Avatar answered Dec 11 '22 15:12

Nina Scholz


One method is to use splice method. str.splice(index, 0, item); will insert item into str at the specified index (deleting 0 items first, that is, it's just an insert).

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

View more here: Array.splice

Please try this:

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);

Here is another method:

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);
like image 44
Mihai Alexandru-Ionut Avatar answered Dec 11 '22 15:12

Mihai Alexandru-Ionut