2

There are two arrays, for example:

arr1 = ["a", "b"];
arr2 = ["c", "d"];

I want to add the elements of the second one to the first one, after this operation arr1 should look like ["a", "b", "c", "d"]. Doesn't matter what happens with arr2.

I tried the classic method: arr1.push(arr2) and the result looks like: ["a", "b", Array(2)].

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • `arr1.push(...arr2)`. Because if you give an array to `push`, that's what's pushed; you need to push its elements. – Amadan Sep 04 '18 at 08:57
  • Another possible dupe: https://stackoverflow.com/questions/3975170/javascript-how-to-join-combine-two-arrays-to-concatenate-into-one-array – Rajesh Sep 04 '18 at 09:03

3 Answers3

8

You can use ES6 syntax for make this :

You can make something like that :

const arr1 = ["a", "b"];
const arr2 = ["c", "d"];

arr1 = [...arr1,...arr2]

console.log(arr1)

Definition about the spread operator :

Allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. (Definition came from MDN)

In ES5 syntax you should using the .concat() function, but it's more easier in ES6 now

KolaCaine
  • 2,037
  • 5
  • 19
  • 31
  • 1
    Please note that if you know the solution and if its obvious, there is a possibility that its been addressed already. So you should look for such posts and post its link in comment section until you have earned privilege to close yourself. – Rajesh Sep 04 '18 at 09:06
6

Use Array.prototype.concat()

var arr1 = ["a", "b"];
var arr2 = ["c", "d"];
arr1 = arr1.concat(arr2);
console.log(arr1)
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Use spread syntax:

var arr1 = ["a", "b"];
var arr2 = ["c", "d"];
arr1 = [...arr1,...arr2];
console.log(arr1);

Use Array.concat():

var arr1 = ["a", "b"];
var arr2 = ["c", "d"];
arr1 = arr1.concat(arr2);
console.log(arr1);
deceze
  • 510,633
  • 85
  • 743
  • 889
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • Note that this is non-destructive, while OP tried to do the destructive method. I do not know if he cares or not, just note it's different. – Amadan Sep 04 '18 at 08:58