Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.push() doesn't work as expected [duplicate]

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
like image 921
user1584421 Avatar asked Jun 28 '26 08:06

user1584421


2 Answers

You should try with:

array2 = array2.concat(array1);

or with ES6 destructuring

array2.push(...array1);
like image 187
hsz Avatar answered Jun 30 '26 23:06

hsz


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"]
like image 21
pyb Avatar answered Jun 30 '26 22:06

pyb