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)]
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With