How to Join Two Arrays Together in JavaScript
Need to combine two arrays into one array? Here’s how you join arrays together in JavaScript, something that is known formally as “array concatenation.”
Joining Together Arrays in JavaScript
When you’re working with two or more JavaScript arrays, you will frequently run into the issue that you wish you had just one array to work with.
For example, we might have a list of users who signed up for our free service as well as a separate list of users who signed up for our paid service.
If we want to find the unique email addresses among all of those users, we’d want to combine the arrays before finding the unique property values.
To keep the metaphor going, we’d want to make a single users
array that combined together the freeUsers
and paidUsers
arrays. Then, we could search all of those user
objects for unique values for the email
property.
In order to join the two arrays, freeUsers
and paidUsers
, we can use either .concat()
or the ...
spread operator. Both methods will achieve the same result, but the syntax is quite a bit different between the two.