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?
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);
You might be looking for this:
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);
Mutating existing values is almost always a bad idea. Just concat things you need together:
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)
You can use slice
method to split the str
array in 2: the part before the insertion point and the part after:
var before = str.slice(0,2);
var after = str.slice(2);
Then you can use concat
method to create the strNum
array, concatenating the before
, num
and after
arrays into 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);