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?
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 giventhis
value andarguments
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);
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);
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