-3

I have an first array and the second array with elements I want to add to the first array

arr1 = [ 1, 2, 3 ];
arr2 = [ 4, 5, 6 ];

arr1.push(arr2);  // [ 1, 2, 3, [ 4, 5, 6]]  but i need [ 1, 2, 3, 4, 5, 6 ]

How can I do it?

  • [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) is likely what you want to use – smcd Dec 06 '20 at 18:28
  • arr1.concat(arr2); – Ballon Ura Dec 06 '20 at 18:28
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+merge+two+arrays) of [JavaScript: How to join / combine two arrays to concatenate into one array?](https://stackoverflow.com/a/3975179/4642212). – Sebastian Simon Dec 06 '20 at 18:36

2 Answers2

4

Either, modify the array and use .concat:

arr1 = arr1.concat(arr2)

Or, push with the spread operator:

arr1.push(...arr2)
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

You can do it with spread operator:

arr1 = [...arr1, ...arr2];
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Yoann Bdl
  • 15
  • 5