2

I have an array. For test purposes i output its contents like this:

for (var i=0; i<array1.length; i++){
        console.log(i + ':' + array1[i]);
    }


0:String1
1:String2

Now i have a second array. What i want to do is push the contents of array1, into array2.

I do this with this line:

array2.push(array1);

Unfortunately, the contents aof the first array, exist in only one index of the second array. Separated by commas.

For example, if we use view the contents of the second array after the action it will be something like this:

for (var i=0; i<array1.length; i++){
        console.log(i + ':' + array1[i]);
    }


0:Old_string1
1:Old_string2
2:Old_string3
3:Old_string4
4:String1,String2

While i would like this outout:

4:String1
5:String2
3
  • Spread with ...: array2.push(...array1).
    – zero298
    Commented Jul 30, 2018 at 14:30
  • 1
    You could use array2.concat(array1)
    – Pete
    Commented Jul 30, 2018 at 14:31
  • hi, can you please elaborate with an example of input and the output you want? Commented Jul 30, 2018 at 14:32

5 Answers 5

5

You should try with:

array2 = array2.concat(array1);

or with ES6 destructuring

array2.push(...array1);
2
  • The solution here is good, but the answer lacks an explanation of why OP's current solution doesn't work. If only we could join this and gkgkgkgk's answer :)
    – noppa
    Commented Jul 30, 2018 at 14:35
  • Plus one for recommending the ES6 syntax :-)
    – pyb
    Commented Jul 30, 2018 at 14:39
4

Array.push doesn't do that. You need Array.concat :

var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
1
  • 1
    It's worth mentioning that concat creates a new array. it does not change existing ones.
    – Nondv
    Commented Jul 30, 2018 at 14:34
3

array.push will push one or more objects to the array. You can not pass a full array in the push() method, or the contents will be counted as one object. To combine the two arrays into one, use concat.

1

You should use the spread operator (...) to destruct the values held in array1 and push those into array2. Like so:

array2.push(...array1);

This will separate all the strings held in array1 into individual values and then push them in. A nice little bit of syntactic sugar introduced in ES6.

1

Use push and apply:

const a1 = ["all", "my", "strings"];
const a2 = ["belong", "together"];
Array.prototype.push.apply(a1, a2);
console.log(a1);

Not the answer you're looking for? Browse other questions tagged or ask your own question.