How to join two arrays in JavaScript
By Flavio Copes
Learn how to join two arrays in JavaScript into a single new array, using the modern spread operator or the concat() method that works in older browsers.
To join two arrays in JavaScript, spread both into a new array: [...first, ...second]. If you need to support older browsers, use first.concat(second). Both create a new array and leave the originals untouched.
Suppose you have two arrays:
const first = ['one', 'two']
const second = ['three', 'four']
and you want to merge them into one single array.
The modern way is to use the spread operator, to create a brand new array:
const result = [...first, ...second]
// ['one', 'two', 'three', 'four']
This is what I recommend. Note that this operator was introduced in ES6, so older browsers (read: Internet Explorer) might not support it.
If you want a solution that works also with older browsers, you could use the concat() method which can be called on any array:
const result = first.concat(second)
Both methods generate a new array, without modifying the existing ones.
Joining more than two arrays
Both approaches scale beyond two arrays. With spread, just add more:
const third = ['five', 'six']
const result = [...first, ...second, ...third]
concat() accepts multiple arguments:
const result = first.concat(second, third)
concat() also accepts plain values, which get appended as single items:
first.concat('five')
// ['one', 'two', 'five']
What if you want to modify the first array?
Sometimes you don’t want a new array. You want to append the items of second to first, in place. Use push() with the spread operator:
first.push(...second)
// first is now ['one', 'two', 'three', 'four']
push() mutates first and returns the new length, not the array.
Be careful with this one on very large arrays. The spread passes each item as a separate function argument, and engines cap how many arguments a call can take. With hundreds of thousands of items you can hit a RangeError. In that case, stick to const result = first.concat(second) or a plain loop.
What about duplicates?
Neither spread nor concat() removes duplicates. If both arrays contain 'two', the result contains it twice.
If you want a merged array of unique values, pass the result through a Set:
const a = ['one', 'two']
const b = ['two', 'three']
const merged = [...new Set([...a, ...b])]
// ['one', 'two', 'three']
The Set drops the duplicate values, and the outer spread turns it back into an array.
Related posts about js: