How to merge two arrays in JavaScript
Merging arrays is essential when combining data from multiple sources, concatenating user selections, or building unified datasets in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented array merging extensively in components like multi-select filters, data aggregation systems, and navigation builders where multiple arrays need to be combined. From my extensive expertise, the most modern and efficient solution is using the ES6 spread operator, which creates a new array without mutating the original arrays. This approach is clean, readable, and performs well for most use cases.
Use the spread operator to merge two arrays into a new array.
const fruits = ['apple', 'banana']
const vegetables = ['carrot', 'broccoli']
const combined = [...fruits, ...vegetables]
// Result: ['apple', 'banana', 'carrot', 'broccoli']
The spread operator ...
expands each array’s elements into the new array literal. In this example, ...fruits
expands to ‘apple’, ‘banana’ and ...vegetables
expands to ‘carrot’, ‘broccoli’, creating a new array with all elements in order. This method doesn’t modify the original arrays and allows you to easily merge multiple arrays by adding more spread operators. You can also insert additional elements between arrays: [...fruits, 'tomato', ...vegetables]
.
Best Practice Note:
This is the same approach we use in CoreUI components for combining configuration arrays and merging user preferences.
For very large arrays, consider using concat()
for better performance: fruits.concat(vegetables)
. The spread operator is ideal for readability and when you need to merge multiple arrays or insert elements during merging.