4

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?

shakib
  • 5,449
  • 2
  • 30
  • 39
Serhiy
  • 1,893
  • 9
  • 30
  • 48

5 Answers5

7

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
6

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);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

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

https://jsfiddle.net/qbkqspqq/

Peachyz
  • 146
  • 7
1

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)
georg
  • 211,518
  • 52
  • 313
  • 390
0

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);
Andrea
  • 3,370
  • 1
  • 17
  • 25