4

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)].

2
  • 1
    arr1.push(...arr2). Because if you give an array to push, that's what's pushed; you need to push its elements. Commented Sep 4, 2018 at 8:57
  • Another possible dupe: stackoverflow.com/questions/3975170/… Commented Sep 4, 2018 at 9:03

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
8

Use Array.prototype.concat()

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

Comments

2

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.