Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To append one array to another:
const arr3 = [...arr1, ...arr2]
.const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = [...arr1, ...arr2]; console.log(arr3); // 👉️ ['a', 'b', 'c', 'd']
We used the spread operator (...) to unpack the values of two arrays into a third array.
The easiest way to think about it is:
arr1
and add them to arr3
.arr2
and add them to arr3
.arr1
and arr2
.Note that the order is preserved and all of the elements of arr1
come before
the elements of arr2
.
The spread operator is commonly used when you need to add new elements to an array without changing the contents of the original array.
const arr1 = ['a', 'b']; const arr2 = [...arr2, 'c', 'd']; console.log(arr3); // 👉️ ['a', 'b', 'c', 'd']
Alternatively, you can use the Array.concat()
method.
To append one array to another, call the concat()
method on the first array,
passing it the second array as a parameter, e.g.
const arr3 = arr1.concat(arr2)
. The concat
method will merge the two arrays
and will return a new array.
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = arr1.concat(arr2); console.log(arr3); // 👉️ ['a', 'b', 'c', 'd']
We used the Array.concat method to merge two arrays into a third.
The method does not change the contents of the original arrays, instead it returns a new array.
The method takes the array(s) you want to concatenate into the new array as parameters.
Here's an example of calling the concat
method with multiple arrays.
const arr1 = ['a', 'b']; const arr2 = arr1.concat(['c'], ['d'], ['e']); console.log(arr2); // 👉️ ['a', 'b', 'c', 'd', 'e']
All of the arrays we passed to the concat
method, including arr1
got merged
into a new array.
You can even pass non-array values to the concat
method.
const arr1 = ['a', 'b']; const arr2 = arr1.concat('c', 'd', ['e']); console.log(arr2); // 👉️ ['a', 'b', 'c', 'd', 'e']
We passed two strings and an array to the concat
method and they all got
merged into the new array.
An alternative approach is to use the push
method to append one array to
another.
To append one array to another, use the push()
method on the first array,
passing it the values of the second array. The push
method is used to add one
or more elements to the end of an array. The method changes the contents of the
original array.
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; arr1.push(...arr2); console.log(arr1); // 👉️ ['a', 'b', 'c', 'd', 'e']
We used the spread operator (...) to unpack the values of arr2
when calling
the
Array.push
method.
The push
method takes one or more values as parameters. The parameters get
pushed to the end of the array.
The method returns the new length of the array and mutates the array's contents.
Which approach you pick is a matter of personal preference. I'd use the spread syntax (...) as I find it the most intuitive and the easiest to read.