Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements of an array to another array [duplicate]

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

like image 987
Leo Messi Avatar asked Sep 11 '25 21:09

Leo Messi


1 Answers

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

like image 63
KolaCaine Avatar answered Sep 13 '25 11:09

KolaCaine